-
Notifications
You must be signed in to change notification settings - Fork 261
/
adb.ts
336 lines (301 loc) · 12.1 KB
/
adb.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
import * as path from "path";
import * as fs from "fs";
import * as os from "os";
import * as nls from "vscode-nls";
import { ILogger } from "../log/LogHelper";
import { CommandExecutor } from "../../common/commandExecutor";
import { ChildProcess, ISpawnResult } from "../../common/node/childProcess";
import { PromiseUtil } from "../../common/node/promise";
import { IDebuggableMobileTarget } from "../mobileTarget";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
// See android versions usage at: http://developer.android.com/about/dashboards/index.html
export enum AndroidAPILevel {
Marshmallow = 23,
LOLLIPOP_MR1 = 22,
LOLLIPOP = 21 /* Supports adb reverse */,
KITKAT = 19,
JELLY_BEAN_MR2 = 18,
JELLY_BEAN_MR1 = 17,
JELLY_BEAN = 16,
ICE_CREAM_SANDWICH_MR1 = 15,
GINGERBREAD_MR1 = 10,
}
enum KeyEvents {
KEYCODE_BACK = 4,
KEYCODE_DPAD_UP = 19,
KEYCODE_DPAD_DOWN = 20,
KEYCODE_DPAD_CENTER = 23,
KEYCODE_MENU = 82,
}
export class AdbHelper {
private nodeModulesRoot: string;
private launchActivity: string;
private childProcess: ChildProcess = new ChildProcess();
private commandExecutor: CommandExecutor;
private adbExecutable: string = "";
private static readonly AndroidRemoteTargetPattern =
/^((?:\d{1,3}\.){3}\d{1,3}:\d{1,5}|.*_adb-tls-con{2}ect\._tcp.*)$/gm;
public static readonly AndroidSDKEmulatorPattern = /^emulator-\d{1,5}$/;
constructor(
projectRoot: string,
nodeModulesRoot: string,
logger?: ILogger,
launchActivity: string = "MainActivity",
) {
this.nodeModulesRoot = nodeModulesRoot;
this.adbExecutable = this.getAdbPath(projectRoot, logger);
this.commandExecutor = new CommandExecutor(this.nodeModulesRoot);
this.launchActivity = launchActivity;
}
/**
* Gets the list of Android connected devices and emulators.
*/
public async getConnectedTargets(): Promise<IDebuggableMobileTarget[]> {
const output = await this.childProcess.execToString(`${this.adbExecutable} devices`);
return this.parseConnectedTargets(output);
}
public async findOnlineTargetById(
targetId: string,
): Promise<IDebuggableMobileTarget | undefined> {
return (await this.getOnlineTargets()).find(target => target.id === targetId);
}
public async getAvdsNames(): Promise<string[]> {
const res = await this.childProcess.execToString("emulator -list-avds");
let emulatorsNames: string[] = [];
if (res) {
emulatorsNames = res.split(/\r?\n|\r/g);
const indexOfBlank = emulatorsNames.indexOf("");
if (indexOfBlank >= 0) {
emulatorsNames.splice(indexOfBlank, 1);
}
}
return emulatorsNames;
}
public isRemoteTarget(id: string): boolean {
return !!id.match(AdbHelper.AndroidRemoteTargetPattern);
}
public async getAvdNameById(emulatorId: string): Promise<string | null> {
try {
const output = await this.childProcess.execToString(
`${this.adbExecutable} -s ${emulatorId} emu avd name`,
);
// The command returns the name of avd by id of this running emulator.
// Return value example:
// "
// emuName
// OK
// "
return output ? output.split(/\r?\n|\r/g)[0] : null;
} catch {
// If the command returned an error, it means that we could not find the emulator with the passed id
return null;
}
}
public setLaunchActivity(launchActivity: string): void {
this.launchActivity = launchActivity;
}
/**
* Broadcasts an intent to reload the application in debug mode.
*/
public async switchDebugMode(
projectRoot: string,
packageName: string,
enable: boolean,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const enableDebugCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am broadcast -a "${packageName}.RELOAD_APP_ACTION" --ez jsproxy ${String(enable)}`;
await new CommandExecutor(this.nodeModulesRoot, projectRoot).execute(enableDebugCommand);
// We should stop and start application again after RELOAD_APP_ACTION, otherwise app going to hangs up
await PromiseUtil.delay(200); // We need a little delay after broadcast command
await this.stopApp(projectRoot, packageName, debugTarget, appIdSuffix);
return this.launchApp(projectRoot, packageName, debugTarget, appIdSuffix);
}
/**
* Sends an intent which launches the main activity of the application.
*/
public launchApp(
projectRoot: string,
packageName: string,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const launchAppCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am start -n ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}/${packageName}.${
this.launchActivity
}`;
return new CommandExecutor(projectRoot).execute(launchAppCommand);
}
public stopApp(
projectRoot: string,
packageName: string,
debugTarget?: string,
appIdSuffix?: string,
): Promise<void> {
const stopAppCommand = `${this.adbExecutable} ${
debugTarget ? `-s ${debugTarget}` : ""
} shell am force-stop ${packageName}${appIdSuffix ? `.${appIdSuffix}` : ""}`;
return new CommandExecutor(projectRoot).execute(stopAppCommand);
}
public async apiVersion(deviceId: string): Promise<AndroidAPILevel> {
const output = await this.executeQuery(deviceId, "shell getprop ro.build.version.sdk");
return parseInt(output, 10);
}
public reverseAdb(deviceId: string, port: number): Promise<void> {
return this.execute(deviceId, `reverse tcp:${port} tcp:${port}`);
}
public showDevMenu(deviceId?: string): Promise<void> {
const command = `${this.adbExecutable} ${
deviceId ? `-s ${deviceId}` : ""
} shell input keyevent ${KeyEvents.KEYCODE_MENU}`;
return this.commandExecutor.execute(command);
}
public reloadApp(deviceId?: string): Promise<void> {
const command = `${this.adbExecutable} ${
deviceId ? `-s ${deviceId}` : ""
} shell input text "RR"`;
return this.commandExecutor.execute(command);
}
public async getOnlineTargets(): Promise<IDebuggableMobileTarget[]> {
const devices = await this.getConnectedTargets();
return devices.filter(device => device.isOnline);
}
public startLogCat(adbParameters: string[]): ISpawnResult {
return this.childProcess.spawn(this.adbExecutable.replace(/"/g, ""), adbParameters);
}
public parseSdkLocation(fileContent: string, logger?: ILogger): string | null {
const matches = fileContent.match(/^sdk\.dir\s*=(.+)$/m);
if (!matches || !matches[1]) {
if (logger) {
logger.info(
localize(
"NoSdkDirFoundInLocalPropertiesFile",
"No sdk.dir value found in local.properties file. Using Android SDK location from PATH.",
),
);
}
return null;
}
let sdkLocation = matches[1].trim();
if (os.platform() === "win32") {
// For Windows we need to unescape files separators and drive letter separators
sdkLocation = sdkLocation.replace(/\\\\/g, "\\").replace("\\:", ":");
}
if (logger) {
logger.info(
localize(
"UsindAndroidSDKLocationDefinedInLocalPropertiesFile",
"Using Android SDK location defined in android/local.properties file: {0}.",
sdkLocation,
),
);
}
return sdkLocation;
}
public getAdbPath(projectRoot: string, logger?: ILogger): string {
const sdkLocation = this.getSdkLocationFromLocalPropertiesFile(projectRoot, logger);
if (sdkLocation) {
const localPropertiesSdkPath = path.join(
sdkLocation as string,
"platform-tools",
os.platform() === "win32" ? "adb.exe" : "adb",
);
const isExist = fs.existsSync(localPropertiesSdkPath);
if (isExist) {
return `"${localPropertiesSdkPath}"`;
}
if (logger) {
logger.warning(
localize(
"LocalPropertiesAndroidSDKPathNotExistingInLocal",
"Local.properties file has Andriod SDK path but cannot find it in your local, will switch to SDK PATH in environment variable. Please check Android SDK path in android/local.properties file.",
),
);
}
return "adb";
}
return "adb";
}
public executeShellCommand(deviceId: string, command: string): Promise<string> {
return this.executeQuery(deviceId, `shell "${command}"`);
}
public installApplicationToEmulator(appPath: string): Promise<string> {
return this.childProcess.execToString(`adb install ${appPath}`);
}
public executeQuery(deviceId: string, command: string): Promise<string> {
return this.childProcess.execToString(this.generateCommandForTarget(deviceId, command));
}
private parseConnectedTargets(input: string): IDebuggableMobileTarget[] {
const result: IDebuggableMobileTarget[] = [];
const regex = new RegExp("^(\\S+)\\t(\\S+)$", "mg");
let match = regex.exec(input);
while (match != null) {
result.push({
id: match[1],
isOnline: match[2] === "device",
isVirtualTarget: this.isVirtualTarget(match[1]),
});
match = regex.exec(input);
}
return result;
}
public isVirtualTarget(id: string): boolean {
return !!id.match(AdbHelper.AndroidSDKEmulatorPattern);
}
private execute(deviceId: string, command: string): Promise<void> {
return this.commandExecutor.execute(this.generateCommandForTarget(deviceId, command));
}
private generateCommandForTarget(deviceId: string, adbCommand: string): string {
return `${this.adbExecutable} -s "${deviceId}" ${adbCommand}`;
}
private getSdkLocationFromLocalPropertiesFile(
projectRoot: string,
logger?: ILogger,
): string | null {
const localPropertiesFilePath = path.join(projectRoot, "android", "local.properties");
if (!fs.existsSync(localPropertiesFilePath)) {
if (logger) {
logger.info(
localize(
"LocalPropertiesFileDoesNotExist",
"local.properties file doesn't exist. Using Android SDK location from PATH.",
),
);
}
return null;
}
let fileContent: string;
try {
fileContent = fs.readFileSync(localPropertiesFilePath).toString();
} catch (e) {
if (logger) {
logger.error(
localize(
"CouldNotReadFrom",
"Couldn't read from {0}.",
localPropertiesFilePath,
),
e,
e.stack,
);
logger.info(
localize(
"UsingAndroidSDKLocationFromPATH",
"Using Android SDK location from PATH.",
),
);
}
return null;
}
return this.parseSdkLocation(fileContent, logger);
}
}