-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathandroid-tools-info.ts
675 lines (593 loc) · 19.8 KB
/
android-tools-info.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
import { ChildProcess } from "./wrappers/child-process";
import { FileSystem } from "./wrappers/file-system";
import { HostInfo } from "./host-info";
import { Constants } from "./constants";
import { Helpers } from "./helpers";
import { EOL } from "os";
import * as semver from "semver";
import * as path from "path";
import * as _ from "lodash";
export class AndroidToolsInfo implements NativeScriptDoctor.IAndroidToolsInfo {
public readonly ANDROID_TARGET_PREFIX = "android";
public getSupportedTargets(projectDir: string) {
const runtimeVersion = this.getRuntimeVersion({ projectDir });
let baseTargets = [
"android-17",
"android-18",
"android-19",
"android-20",
"android-21",
"android-22",
"android-23",
"android-24",
"android-25",
"android-26",
"android-27",
"android-28",
"android-29",
"android-30",
"android-31",
"android-32",
"android-33",
"android-34",
"android-35",
];
const isRuntimeVersionLessThan = (targetVersion: string) => {
return (
runtimeVersion &&
semver.lt(semver.coerce(runtimeVersion), targetVersion)
);
};
if (isRuntimeVersionLessThan("6.1.0")) {
// limit baseTargets to android-17 - android-28 if the runtime is < 6.1.0
baseTargets = baseTargets.slice(0, baseTargets.indexOf("android-29"));
} else if (isRuntimeVersionLessThan("8.2.0")) {
// limit baseTargets to android-17 - android-30 if the runtime is < 8.2.0
baseTargets = baseTargets.slice(0, baseTargets.indexOf("android-31"));
}
return baseTargets;
}
private static MIN_REQUIRED_COMPILE_TARGET = 28;
private static REQUIRED_BUILD_TOOLS_RANGE_PREFIX = ">=23";
private static VERSION_REGEX = /((\d+\.){2}\d+)/;
private static MIN_JAVA_VERSION = "1.8.0";
// If some java release breaks the code then set this version to the breaking release (e.g. "13.0.0")
private static MAX_JAVA_VERSION = null as string;
private toolsInfo: NativeScriptDoctor.IAndroidToolsInfoData;
public get androidHome(): string {
return process.env["ANDROID_HOME"];
}
private pathToEmulatorExecutable: string;
private _cachedRuntimeVersion: string;
constructor(
private childProcess: ChildProcess,
private fs: FileSystem,
private hostInfo: HostInfo,
private helpers: Helpers
) {}
public getToolsInfo(
config: Partial<NativeScriptDoctor.IProjectDir> = {}
): NativeScriptDoctor.IAndroidToolsInfoData {
if (!this.toolsInfo) {
const infoData: NativeScriptDoctor.IAndroidToolsInfoData =
Object.create(null);
infoData.androidHomeEnvVar = this.androidHome;
infoData.installedTargets = this.getInstalledTargets();
infoData.compileSdkVersion = this.getCompileSdk(
infoData.installedTargets,
config.projectDir
);
infoData.buildToolsVersion = this.getBuildToolsVersion(config.projectDir);
this.toolsInfo = infoData;
}
return this.toolsInfo;
}
public validateInfo(
config: Partial<NativeScriptDoctor.IProjectDir> = {}
): NativeScriptDoctor.IWarning[] {
const errors: NativeScriptDoctor.IWarning[] = [];
const toolsInfoData = this.getToolsInfo(config);
const isAndroidHomeValid = this.isAndroidHomeValid();
if (!toolsInfoData.compileSdkVersion) {
const supportedTargetsForAndroidRuntime = this.getSupportedTargets(
config.projectDir
);
errors.push({
warning: [
`Cannot find a compatible Android SDK for compilation.`,
`To be able to build for Android with your current android runtime, install one of the following supported Android SDK targets:`,
...supportedTargetsForAndroidRuntime.map((target) => ` ${target}`),
`Supported targets vary based on what android runtime you have installed. Currently your app uses @nativescript/android ${this.getRuntimeVersion(
{ projectDir: config.projectDir }
)}`,
].join("\n"),
additionalInformation: `Run \`\$ ${this.getPathToSdkManagementTool()}\` to manage your Android SDK versions.`,
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
if (!toolsInfoData.buildToolsVersion) {
const buildToolsRange = this.getBuildToolsRange(config.projectDir);
const versionRangeMatches = buildToolsRange.match(
/^.*?([\d\.]+)\s+.*?([\d\.]+)$/
);
let message = `You can install any version in the following range: '${buildToolsRange}'.`;
// Improve message in case buildToolsRange is something like: ">=22.0.0 <=22.0.0" - same numbers on both sides
if (
versionRangeMatches &&
versionRangeMatches[1] &&
versionRangeMatches[2] &&
versionRangeMatches[1] === versionRangeMatches[2]
) {
message = `You have to install version ${versionRangeMatches[1]}.`;
}
// let invalidBuildToolsAdditionalMsg = `Run \`\$ ${this.getPathToSdkManagementTool()}\` from your command-line to install required \`Android Build Tools\`.`;
let invalidBuildToolsAdditionalMsg = `Install the required build-tools through Android Studio.`;
if (!isAndroidHomeValid) {
invalidBuildToolsAdditionalMsg +=
" In case you already have them installed, make sure the `ANDROID_HOME` environment variable is set correctly.";
}
errors.push({
warning:
"No compatible version of the Android SDK Build-tools are installed on your system. " +
message,
additionalInformation: invalidBuildToolsAdditionalMsg,
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
return errors;
}
public static unsupportedJavaMessage(
installedJavaCompilerVersion: string
): string {
return `Javac version ${installedJavaCompilerVersion} is not supported. You must install a java version greater than ${
AndroidToolsInfo.MIN_JAVA_VERSION
}${
AndroidToolsInfo.MAX_JAVA_VERSION
? ` and less than ${AndroidToolsInfo.MAX_JAVA_VERSION}`
: ""
}.`;
}
public validateJavacVersion(
installedJavaCompilerVersion: string,
projectDir?: string,
runtimeVersion?: string
): NativeScriptDoctor.IWarning[] {
const errors: NativeScriptDoctor.IWarning[] = [];
let additionalMessage =
"You will not be able to build your projects for Android." +
EOL +
"To be able to build for Android, verify that you have installed The Java Development Kit (JDK) and configured it according to system requirements as" +
EOL +
" described in " +
this.getSystemRequirementsLink();
const matchingVersion = this.helpers
.appendZeroesToVersion(installedJavaCompilerVersion || "", 3)
.match(AndroidToolsInfo.VERSION_REGEX);
const installedJavaCompilerSemverVersion =
matchingVersion && matchingVersion[1];
if (installedJavaCompilerSemverVersion) {
let warning: string = null;
const supportedVersions: IDictionary<string> = {
"^10.0.0": "4.1.0-2018.5.18.1",
};
if (
semver.lt(
installedJavaCompilerSemverVersion,
AndroidToolsInfo.MIN_JAVA_VERSION
) ||
(AndroidToolsInfo.MAX_JAVA_VERSION
? semver.gte(
installedJavaCompilerSemverVersion,
AndroidToolsInfo.MAX_JAVA_VERSION
)
: false)
) {
warning = AndroidToolsInfo.unsupportedJavaMessage(
installedJavaCompilerVersion
);
} else {
runtimeVersion = this.getRuntimeVersion({ runtimeVersion, projectDir });
if (runtimeVersion) {
// get the item from the dictionary that corresponds to our current Javac version:
let runtimeMinVersion: string = null;
Object.keys(supportedVersions).forEach((javacRange) => {
if (
semver.satisfies(installedJavaCompilerSemverVersion, javacRange)
) {
runtimeMinVersion = supportedVersions[javacRange];
}
});
if (
runtimeMinVersion &&
semver.lt(runtimeVersion, runtimeMinVersion)
) {
warning =
`The Java compiler version ${installedJavaCompilerVersion} is not compatible with the current Android runtime version ${runtimeVersion}. ` +
`In order to use this Javac version, you need to update your Android runtime or downgrade your Java compiler version.`;
additionalMessage =
"You will not be able to build your projects for Android." +
EOL +
"To be able to build for Android, downgrade your Java compiler version or update your Android runtime.";
}
}
}
if (warning) {
errors.push({
warning,
additionalInformation: additionalMessage,
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
} else {
errors.push({
warning:
"Error executing command 'javac'. Make sure you have installed The Java Development Kit (JDK) and set JAVA_HOME environment variable.",
additionalInformation: additionalMessage,
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
return errors;
}
public async getPathToAdbFromAndroidHome(): Promise<string> {
if (this.androidHome) {
const pathToAdb = path.join(this.androidHome, "platform-tools", "adb");
try {
await this.childProcess.execFile(pathToAdb, ["help"]);
return pathToAdb;
} catch (err) {
return null;
}
}
return null;
}
public validateAndroidHomeEnvVariable(): NativeScriptDoctor.IWarning[] {
const errors: NativeScriptDoctor.IWarning[] = [];
const expectedDirectoriesInAndroidHome = [
"build-tools",
"tools",
"platform-tools",
"extras",
];
if (!this.androidHome || !this.fs.exists(this.androidHome)) {
errors.push({
warning:
"The ANDROID_HOME environment variable is not set or it points to a non-existent directory. You will not be able to perform any build-related operations for Android.",
additionalInformation:
"To be able to perform Android build-related operations, set the `ANDROID_HOME` variable to point to the root of your Android SDK installation directory.",
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
} else if (
expectedDirectoriesInAndroidHome.map((dir) =>
this.fs.exists(path.join(this.androidHome, dir))
).length === 0
) {
errors.push({
warning:
"The ANDROID_HOME environment variable points to incorrect directory. You will not be able to perform any build-related operations for Android.",
additionalInformation:
"To be able to perform Android build-related operations, set the `ANDROID_HOME` variable to point to the root of your Android SDK installation directory, " +
"where you will find `tools` and `platform-tools` directories.",
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
return errors;
}
public validateMinSupportedTargetSdk({
targetSdk,
projectDir,
}: NativeScriptDoctor.ITargetValidationOptions): NativeScriptDoctor.IWarning[] {
const errors: NativeScriptDoctor.IWarning[] = [];
const newTarget = `${this.ANDROID_TARGET_PREFIX}-${targetSdk}`;
const supportedTargets = this.getSupportedTargets(projectDir);
const targetSupported = _.includes(supportedTargets, newTarget);
if (!_.includes(supportedTargets, newTarget)) {
const supportedVersions = supportedTargets.sort();
const minSupportedVersion = this.parseAndroidSdkString(
_.first(supportedVersions)
);
if (!targetSupported && targetSdk && targetSdk < minSupportedVersion) {
errors.push({
warning: `The selected Android target SDK ${newTarget} is not supported. You must target ${minSupportedVersion} or later.`,
additionalInformation: "",
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
}
return errors;
}
public validataMaxSupportedTargetSdk({
targetSdk,
projectDir,
}: NativeScriptDoctor.ITargetValidationOptions): NativeScriptDoctor.IWarning[] {
const errors: NativeScriptDoctor.IWarning[] = [];
const newTarget = `${this.ANDROID_TARGET_PREFIX}-${targetSdk}`;
const targetSupported = _.includes(
this.getSupportedTargets(projectDir),
newTarget
);
if (
(!targetSupported && !targetSdk) ||
targetSdk > this.getMaxSupportedVersion(projectDir)
) {
errors.push({
warning: `Support for the selected Android target SDK ${newTarget} is not verified. Your Android app might not work as expected.`,
additionalInformation: "",
platforms: [Constants.ANDROID_PLATFORM_NAME],
});
}
return errors;
}
public getPathToEmulatorExecutable(): string {
if (!this.pathToEmulatorExecutable) {
const emulatorExecutableName = "emulator";
this.pathToEmulatorExecutable = emulatorExecutableName;
if (this.androidHome) {
// Check https://developer.android.com/studio/releases/sdk-tools.html (25.3.0)
// Since this version of SDK tools, the emulator is a separate package.
// However the emulator executable still exists in the "tools" dir.
const pathToEmulatorFromAndroidStudio = path.join(
this.androidHome,
emulatorExecutableName,
emulatorExecutableName
);
const realFilePath = this.hostInfo.isWindows
? `${pathToEmulatorFromAndroidStudio}.exe`
: pathToEmulatorFromAndroidStudio;
if (this.fs.exists(realFilePath)) {
this.pathToEmulatorExecutable = pathToEmulatorFromAndroidStudio;
} else {
this.pathToEmulatorExecutable = path.join(
this.androidHome,
"tools",
emulatorExecutableName
);
}
}
}
return this.pathToEmulatorExecutable;
}
private getPathToSdkManagementTool(): string {
const sdkmanagerName = "sdkmanager";
let sdkManagementToolPath = sdkmanagerName;
const isAndroidHomeValid = this.isAndroidHomeValid();
if (isAndroidHomeValid) {
// In case ANDROID_HOME is correct, check if sdkmanager exists and if not it means the SDK has not been updated.
// In this case user shoud use `android` from the command-line instead of sdkmanager.
const pathToSdkmanager = path.join(
this.androidHome,
"tools",
"bin",
sdkmanagerName
);
const pathToAndroidExecutable = path.join(
this.androidHome,
"tools",
"android"
);
const pathToExecutable = this.fs.exists(pathToSdkmanager)
? pathToSdkmanager
: pathToAndroidExecutable;
sdkManagementToolPath = pathToExecutable.replace(
this.androidHome,
this.hostInfo.isWindows ? "%ANDROID_HOME%" : "$ANDROID_HOME"
);
}
return sdkManagementToolPath;
}
private getCompileSdk(
installedTargets: string[],
projectDir: string
): number {
const latestValidAndroidTarget = this.getLatestValidAndroidTarget(
installedTargets,
projectDir
);
if (latestValidAndroidTarget) {
const integerVersion = this.parseAndroidSdkString(
latestValidAndroidTarget
);
if (
integerVersion &&
integerVersion >= AndroidToolsInfo.MIN_REQUIRED_COMPILE_TARGET
) {
return integerVersion;
}
}
}
private getMatchingDir(pathToDir: string, versionRange: string): string {
let selectedVersion: string;
if (this.fs.exists(pathToDir)) {
const subDirs = this.fs.readDirectory(pathToDir);
const subDirsVersions = subDirs
.map((dirName) => {
const dirNameGroups = dirName.match(AndroidToolsInfo.VERSION_REGEX);
if (dirNameGroups) {
return dirNameGroups[1];
}
return null;
})
.filter((dirName) => !!dirName);
const version = semver.maxSatisfying(subDirsVersions, versionRange);
if (version) {
selectedVersion = subDirs.find((dir) => dir.indexOf(version) !== -1);
}
}
return selectedVersion;
}
private getBuildToolsRange(projectDir: string): string {
return `${
AndroidToolsInfo.REQUIRED_BUILD_TOOLS_RANGE_PREFIX
} <=${this.getMaxSupportedVersion(projectDir)}`;
}
private getBuildToolsVersion(projectDir: string): string {
let buildToolsVersion: string;
if (this.androidHome) {
const pathToBuildTools = path.join(this.androidHome, "build-tools");
const buildToolsRange = this.getBuildToolsRange(projectDir);
buildToolsVersion = this.getMatchingDir(
pathToBuildTools,
buildToolsRange
);
}
return buildToolsVersion;
}
private getLatestValidAndroidTarget(
installedTargets: string[],
projectDir: string
): string {
return _.findLast(
this.getSupportedTargets(projectDir).sort(),
(supportedTarget) => _.includes(installedTargets, supportedTarget)
);
}
private parseAndroidSdkString(androidSdkString: string): number {
return parseInt(
androidSdkString.replace(`${this.ANDROID_TARGET_PREFIX}-`, "")
);
}
private getInstalledTargets(): string[] {
try {
const pathToInstalledTargets = path.join(this.androidHome, "platforms");
if (!this.fs.exists(pathToInstalledTargets)) {
throw new Error("No Android Targets installed.");
}
return this.fs.readDirectory(pathToInstalledTargets);
} catch (err) {
return [];
}
}
private getMaxSupportedVersion(projectDir: string): number {
const supportedTargets = this.getSupportedTargets(projectDir);
return this.parseAndroidSdkString(
supportedTargets.sort()[supportedTargets.length - 1]
);
}
private getSystemRequirementsLink(): string {
return Constants.SYSTEM_REQUIREMENTS_LINKS;
}
private isAndroidHomeValid(): boolean {
const errors = this.validateAndroidHomeEnvVariable();
return !errors && !errors.length;
}
private getAndroidRuntimePackageFromProjectDir(projectDir: string): {
name: string;
version: string;
} {
if (!projectDir || !this.fs.exists(projectDir)) {
return null;
}
const pathToPackageJson = path.join(projectDir, Constants.PACKAGE_JSON);
if (!this.fs.exists(pathToPackageJson)) {
return null;
}
const content =
this.fs.readJson<INativeScriptProjectPackageJson>(pathToPackageJson);
if (!content) {
return null;
}
// in case we have a nativescript key and a runtime with a version
// we are dealing with a legacy project and should respect the values
// in the nativescript key
if (
content &&
content.nativescript &&
content.nativescript["tns-android"] &&
content.nativescript["tns-android"].version
) {
return {
name: Constants.ANDROID_OLD_RUNTIME,
version:
content.nativescript &&
content.nativescript["tns-android"] &&
content.nativescript["tns-android"].version,
};
}
if (content && content.devDependencies) {
const foundRuntime = Object.keys(content.devDependencies).find(
(depName) => {
return (
depName === Constants.ANDROID_SCOPED_RUNTIME ||
depName === Constants.ANDROID_OLD_RUNTIME
);
}
);
if (foundRuntime) {
let version = content.devDependencies[foundRuntime];
if (version.includes("tgz")) {
try {
const packagePath = require.resolve(
`${foundRuntime}/package.json`,
{
paths: [projectDir],
}
);
version = require(packagePath).version;
} catch (err) {
version = "*";
}
}
return {
name: foundRuntime,
version,
};
}
}
return null;
}
private getRuntimeVersion({
runtimeVersion,
projectDir,
}: {
runtimeVersion?: string;
projectDir?: string;
}): string {
if (this._cachedRuntimeVersion) {
return this._cachedRuntimeVersion;
}
let runtimePackage = {
name: Constants.ANDROID_SCOPED_RUNTIME,
version: runtimeVersion,
};
if (!runtimeVersion) {
runtimePackage = this.getAndroidRuntimePackageFromProjectDir(projectDir);
runtimeVersion = runtimePackage && runtimePackage.version;
}
if (runtimeVersion) {
// Check if the version is not "next" or "rc", i.e. tag from npm
if (!semver.validRange(runtimeVersion)) {
try {
const npmViewOutput = this.childProcess.execSync(
`npm view ${runtimePackage.name} dist-tags --json`
);
const jsonNpmViewOutput = JSON.parse(npmViewOutput);
runtimeVersion = jsonNpmViewOutput[runtimeVersion] || runtimeVersion;
} catch (err) {
// Maybe there's no npm here
}
}
}
if (runtimeVersion && !semver.validRange(runtimeVersion)) {
// If we got here, something terribly wrong happened.
throw new Error(
`The determined Android runtime version ${runtimeVersion} is not valid. Unable to verify if the current system is setup for Android development.`
);
}
this._cachedRuntimeVersion = runtimeVersion;
return runtimeVersion;
}
private getMaxSupportedCompileVersion(
config: Partial<NativeScriptDoctor.IProjectDir> & {
runtimeVersion?: string;
}
): number {
if (
config.runtimeVersion &&
semver.lt(semver.coerce(config.runtimeVersion), "6.1.0")
) {
return 28;
}
return this.parseAndroidSdkString(
_.last(this.getSupportedTargets(config.projectDir).sort())
);
}
}