android_sdk.dart 16.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import '../base/common.dart';
6
import '../base/file_system.dart';
7
import '../base/process.dart';
8
import '../base/version.dart';
9
import '../convert.dart';
10
import '../globals.dart' as globals;
11
import 'java.dart';
12

13 14
// ANDROID_HOME is deprecated.
// See https://developer.android.com/studio/command-line/variables.html#envar
15
const String kAndroidHome = 'ANDROID_HOME';
16
const String kAndroidSdkRoot = 'ANDROID_SDK_ROOT';
17

18 19
final RegExp _numberedAndroidPlatformRe = RegExp(r'^android-([0-9]+)$');
final RegExp _sdkVersionRe = RegExp(r'^ro.build.version.sdk=([0-9]+)$');
20

21
// Android SDK layout:
22

23
// $ANDROID_SDK_ROOT/platform-tools/adb
24

25 26 27 28 29
// $ANDROID_SDK_ROOT/build-tools/19.1.0/aapt, dx, zipalign
// $ANDROID_SDK_ROOT/build-tools/22.0.1/aapt
// $ANDROID_SDK_ROOT/build-tools/23.0.2/aapt
// $ANDROID_SDK_ROOT/build-tools/24.0.0-preview/aapt
// $ANDROID_SDK_ROOT/build-tools/25.0.2/apksigner
30

31 32 33
// $ANDROID_SDK_ROOT/platforms/android-22/android.jar
// $ANDROID_SDK_ROOT/platforms/android-23/android.jar
// $ANDROID_SDK_ROOT/platforms/android-N/android.jar
34
class AndroidSdk {
35 36 37
  AndroidSdk(this.directory, {
    Java? java,
  }): _java = java {
38
    reinitialize();
39 40
  }

41 42
  /// The Android SDK root directory.
  final Directory directory;
43

44 45
  final Java? _java;

46 47
  List<AndroidSdkVersion> _sdkVersions = <AndroidSdkVersion>[];
  AndroidSdkVersion? _latestVersion;
48

49 50 51 52 53 54
  /// Whether the `cmdline-tools` directory exists in the Android SDK.
  ///
  /// This is required to use the newest SDK manager which only works with
  /// the newer JDK.
  bool get cmdlineToolsAvailable => directory.childDirectory('cmdline-tools').existsSync();

55
  /// Whether the `platform-tools` or `cmdline-tools` directory exists in the Android SDK.
56 57 58 59 60
  ///
  /// It is possible to have an Android SDK folder that is missing this with
  /// the expectation that it will be downloaded later, e.g. by gradle or the
  /// sdkmanager. The [licensesAvailable] property should be used to determine
  /// whether the licenses are at least possibly accepted.
61
  bool get platformToolsAvailable => cmdlineToolsAvailable
62
     || directory.childDirectory('platform-tools').existsSync();
63 64 65 66 67 68 69 70

  /// Whether the `licenses` directory exists in the Android SDK.
  ///
  /// The existence of this folder normally indicates that the SDK licenses have
  /// been accepted, e.g. via the sdkmanager, Android Studio, or by copying them
  /// from another workstation such as in CI scenarios. If these files are valid
  /// gradle or the sdkmanager will be able to download and use other parts of
  /// the SDK on demand.
71
  bool get licensesAvailable => directory.childDirectory('licenses').existsSync();
72

73 74 75
  static AndroidSdk? locateAndroidSdk() {
    String? findAndroidHomeDir() {
      String? androidHomeDir;
76
      if (globals.config.containsKey('android-sdk')) {
77
        androidHomeDir = globals.config.getValue('android-sdk') as String?;
78 79 80 81 82
      } else if (globals.platform.environment.containsKey(kAndroidHome)) {
        androidHomeDir = globals.platform.environment[kAndroidHome];
      } else if (globals.platform.environment.containsKey(kAndroidSdkRoot)) {
        androidHomeDir = globals.platform.environment[kAndroidSdkRoot];
      } else if (globals.platform.isLinux) {
83 84
        if (globals.fsUtils.homeDirPath != null) {
          androidHomeDir = globals.fs.path.join(
85
            globals.fsUtils.homeDirPath!,
86 87 88
            'Android',
            'Sdk',
          );
89
        }
90
      } else if (globals.platform.isMacOS) {
91 92
        if (globals.fsUtils.homeDirPath != null) {
          androidHomeDir = globals.fs.path.join(
93
            globals.fsUtils.homeDirPath!,
94 95 96 97
            'Library',
            'Android',
            'sdk',
          );
98
        }
99
      } else if (globals.platform.isWindows) {
100 101
        if (globals.fsUtils.homeDirPath != null) {
          androidHomeDir = globals.fs.path.join(
102
            globals.fsUtils.homeDirPath!,
103 104 105 106 107
            'AppData',
            'Local',
            'Android',
            'sdk',
          );
108
        }
109 110 111
      }

      if (androidHomeDir != null) {
112
        if (validSdkDirectory(androidHomeDir)) {
113
          return androidHomeDir;
114
        }
115 116
        if (validSdkDirectory(globals.fs.path.join(androidHomeDir, 'sdk'))) {
          return globals.fs.path.join(androidHomeDir, 'sdk');
117
        }
118 119 120
      }

      // in build-tools/$version/aapt
121
      final List<File> aaptBins = globals.os.whichAll('aapt');
122 123
      for (File aaptBin in aaptBins) {
        // Make sure we're using the aapt from the SDK.
124
        aaptBin = globals.fs.file(aaptBin.resolveSymbolicLinksSync());
125
        final String dir = aaptBin.parent.parent.parent.path;
126
        if (validSdkDirectory(dir)) {
127
          return dir;
128
        }
129 130 131
      }

      // in platform-tools/adb
132
      final List<File> adbBins = globals.os.whichAll('adb');
133 134
      for (File adbBin in adbBins) {
        // Make sure we're using the adb from the SDK.
135
        adbBin = globals.fs.file(adbBin.resolveSymbolicLinksSync());
136
        final String dir = adbBin.parent.parent.path;
137
        if (validSdkDirectory(dir)) {
138
          return dir;
139
        }
140 141 142 143 144
      }

      return null;
    }

145
    final String? androidHomeDir = findAndroidHomeDir();
146 147
    if (androidHomeDir == null) {
      // No dice.
148
      globals.printTrace('Unable to locate an Android SDK.');
149
      return null;
150 151
    }

152
    return AndroidSdk(globals.fs.directory(androidHomeDir));
153 154 155
  }

  static bool validSdkDirectory(String dir) {
Lau Ching Jun's avatar
Lau Ching Jun committed
156
    return sdkDirectoryHasLicenses(dir) || sdkDirectoryHasPlatformTools(dir);
157 158 159
  }

  static bool sdkDirectoryHasPlatformTools(String dir) {
160
    return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'platform-tools'));
161 162
  }

Lau Ching Jun's avatar
Lau Ching Jun committed
163
  static bool sdkDirectoryHasLicenses(String dir) {
164
    return globals.fs.isDirectorySync(globals.fs.path.join(dir, 'licenses'));
165 166 167 168
  }

  List<AndroidSdkVersion> get sdkVersions => _sdkVersions;

169
  AndroidSdkVersion? get latestVersion => _latestVersion;
170

171
  late final String? adbPath = getPlatformToolsPath(globals.platform.isWindows ? 'adb.exe' : 'adb');
172

173
  String? get emulatorPath => getEmulatorPath();
174

175
  String? get avdManagerPath => getAvdManagerPath();
176

177
  /// Locate the path for storing AVD emulator images. Returns null if none found.
178 179 180
  String? getAvdPath() {
    final String? avdHome = globals.platform.environment['ANDROID_AVD_HOME'];
    final String? home = globals.platform.environment['HOME'];
181
    final List<String> searchPaths = <String>[
182 183 184 185
      if (avdHome != null)
        avdHome,
      if (home != null)
        globals.fs.path.join(home, '.android', 'avd'),
186 187 188
    ];

    if (globals.platform.isWindows) {
189 190
      final String? homeDrive = globals.platform.environment['HOMEDRIVE'];
      final String? homePath = globals.platform.environment['HOMEPATH'];
191 192 193 194 195 196 197 198 199

      if (homeDrive != null && homePath != null) {
        // Can't use path.join for HOMEDRIVE/HOMEPATH
        // https://github.com/dart-lang/path/issues/37
        final String home = homeDrive + homePath;
        searchPaths.add(globals.fs.path.join(home, '.android', 'avd'));
      }
    }

200
    for (final String searchPath in searchPaths) {
201 202 203 204 205
      if (globals.fs.directory(searchPath).existsSync()) {
        return searchPath;
      }
    }
    return null;
206 207
  }

208
  Directory get _platformsDir => directory.childDirectory('platforms');
209 210 211 212 213 214 215 216 217 218 219

  Iterable<Directory> get _platforms {
    Iterable<Directory> platforms = <Directory>[];
    if (_platformsDir.existsSync()) {
      platforms = _platformsDir
        .listSync()
        .whereType<Directory>();
    }
    return platforms;
  }

220 221
  /// Validate the Android SDK. This returns an empty list if there are no
  /// issues; otherwise, it returns a list of issues found.
222
  List<String> validateSdkWellFormed() {
223
    if (adbPath == null || !globals.processManager.canRun(adbPath)) {
224
      return <String>['Android SDK file not found: ${adbPath ?? 'adb'}.'];
225
    }
226

227 228 229 230 231 232 233 234 235 236 237 238
    if (sdkVersions.isEmpty || latestVersion == null) {
      final StringBuffer msg = StringBuffer('No valid Android SDK platforms found in ${_platformsDir.path}.');
      if (_platforms.isEmpty) {
        msg.write(' Directory was empty.');
      } else {
        msg.write(' Candidates were:\n');
        msg.write(_platforms
          .map((Directory dir) => '  - ${dir.basename}')
          .join('\n'));
      }
      return <String>[msg.toString()];
    }
239

240
    return latestVersion!.validateSdkWellFormed();
241 242
  }

243
  String? getPlatformToolsPath(String binaryName) {
244 245 246 247 248 249 250
    final File cmdlineToolsBinary = directory.childDirectory('cmdline-tools').childFile(binaryName);
    if (cmdlineToolsBinary.existsSync()) {
      return cmdlineToolsBinary.path;
    }
    final File platformToolBinary = directory.childDirectory('platform-tools').childFile(binaryName);
    if (platformToolBinary.existsSync()) {
      return platformToolBinary.path;
251
    }
252
    return null;
253 254
  }

255
  String? getEmulatorPath() {
256
    final String binaryName = globals.platform.isWindows ? 'emulator.exe' : 'emulator';
Danny Tuppeny's avatar
Danny Tuppeny committed
257 258 259 260
    // Emulator now lives inside "emulator" but used to live inside "tools" so
    // try both.
    final List<String> searchFolders = <String>['emulator', 'tools'];
    for (final String folder in searchFolders) {
261 262 263
      final File file = directory.childDirectory(folder).childFile(binaryName);
      if (file.existsSync()) {
        return file.path;
264
      }
Danny Tuppeny's avatar
Danny Tuppeny committed
265 266
    }
    return null;
267 268
  }

269
  String? getCmdlineToolsPath(String binaryName, {bool skipOldTools = false}) {
270 271
    // First look for the latest version of the command-line tools
    final File cmdlineToolsLatestBinary = directory
272 273 274 275
      .childDirectory('cmdline-tools')
      .childDirectory('latest')
      .childDirectory('bin')
      .childFile(binaryName);
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    if (cmdlineToolsLatestBinary.existsSync()) {
      return cmdlineToolsLatestBinary.path;
    }

    // Next look for the highest version of the command-line tools
    final Directory cmdlineToolsDir = directory.childDirectory('cmdline-tools');
    if (cmdlineToolsDir.existsSync()) {
      final List<Version> cmdlineTools = cmdlineToolsDir
        .listSync()
        .whereType<Directory>()
        .map((Directory subDirectory) {
          try {
            return Version.parse(subDirectory.basename);
          } on Exception {
            return null;
          }
        })
293
        .whereType<Version>()
294 295 296 297 298 299 300 301 302 303 304 305 306
        .toList();
      cmdlineTools.sort();

      for (final Version cmdlineToolsVersion in cmdlineTools.reversed) {
        final File cmdlineToolsBinary = directory
          .childDirectory('cmdline-tools')
          .childDirectory(cmdlineToolsVersion.toString())
          .childDirectory('bin')
          .childFile(binaryName);
        if (cmdlineToolsBinary.existsSync()) {
          return cmdlineToolsBinary.path;
        }
      }
307
    }
308 309 310
    if (skipOldTools) {
      return null;
    }
311 312

    // Finally fallback to the old SDK tools
313 314 315
    final File toolsBinary = directory.childDirectory('tools').childDirectory('bin').childFile(binaryName);
    if (toolsBinary.existsSync()) {
      return toolsBinary.path;
316
    }
317

318 319 320
    return null;
  }

321
  String? getAvdManagerPath() => getCmdlineToolsPath(globals.platform.isWindows ? 'avdmanager.bat' : 'avdmanager');
322

323 324 325 326 327
  /// Sets up various paths used internally.
  ///
  /// This method should be called in a case where the tooling may have updated
  /// SDK artifacts, such as after running a gradle build.
  void reinitialize() {
328
    List<Version> buildTools = <Version>[]; // 19.1.0, 22.0.1, ...
329

330
    final Directory buildToolsDir = directory.childDirectory('build-tools');
331
    if (buildToolsDir.existsSync()) {
332
      buildTools = buildToolsDir
333 334 335
        .listSync()
        .map((FileSystemEntity entity) {
          try {
336
            return Version.parse(entity.basename);
337
          } on Exception {
338 339 340
            return null;
          }
        })
341
        .whereType<Version>()
342 343 344
        .toList();
    }

345
    // Match up platforms with the best corresponding build-tools.
346
    _sdkVersions = _platforms.map<AndroidSdkVersion?>((Directory platformDir) {
347
      final String platformName = platformDir.basename;
348
      int platformVersion;
349 350

      try {
351
        final Match? numberedVersion = _numberedAndroidPlatformRe.firstMatch(platformName);
352
        if (numberedVersion != null) {
353
          platformVersion = int.parse(numberedVersion.group(1)!);
354 355
        } else {
          final String buildProps = platformDir.childFile('build.prop').readAsStringSync();
356
          final Iterable<Match> versionMatches = const LineSplitter()
357
              .convert(buildProps)
358
              .map<RegExpMatch?>(_sdkVersionRe.firstMatch)
359 360 361 362 363 364 365
              .whereType<Match>();

          if (versionMatches.isEmpty) {
            return null;
          }

          final String? versionString = versionMatches.first.group(1);
366 367 368
          if (versionString == null) {
            return null;
          }
369 370
          platformVersion = int.parse(versionString);
        }
371
      } on Exception {
372 373 374
        return null;
      }

375
      Version? buildToolsVersion = Version.primary(buildTools.where((Version version) {
376
        return version.major == platformVersion;
377 378
      }).toList());

379 380
      buildToolsVersion ??= Version.primary(buildTools);

381
      if (buildToolsVersion == null) {
382
        return null;
383
      }
384

385
      return AndroidSdkVersion._(
386
        this,
387 388 389
        sdkLevel: platformVersion,
        platformName: platformName,
        buildToolsVersion: buildToolsVersion,
390
        fileSystem: globals.fs,
391
      );
392
    }).whereType<AndroidSdkVersion>().toList();
393 394 395 396 397 398

    _sdkVersions.sort();

    _latestVersion = _sdkVersions.isEmpty ? null : _sdkVersions.last;
  }

399
  /// Returns the filesystem path of the Android SDK manager tool.
400
  String? get sdkManagerPath {
401 402 403
    final String executable = globals.platform.isWindows
      ? 'sdkmanager.bat'
      : 'sdkmanager';
404
    final String? path = getCmdlineToolsPath(executable, skipOldTools: true);
405 406
    if (path != null) {
      return path;
407
    }
408
    return null;
409 410 411
  }

  /// Returns the version of the Android SDK manager tool or null if not found.
412
  String? get sdkManagerVersion {
413 414 415 416 417
    if (sdkManagerPath == null || !globals.processManager.canRun(sdkManagerPath)) {
      throwToolExit(
        'Android sdkmanager not found. Update to the latest Android SDK and ensure that '
        'the cmdline-tools are installed to resolve this.'
      );
418
    }
419
    final RunResult result = globals.processUtils.runSync(
420
      <String>[sdkManagerPath!, '--version'],
421
      environment: _java?.environment,
422
    );
423
    if (result.exitCode != 0) {
424
      globals.printTrace('sdkmanager --version failed: exitCode: ${result.exitCode} stdout: ${result.stdout} stderr: ${result.stderr}');
425
      return null;
426 427 428 429
    }
    return result.stdout.trim();
  }

430
  @override
431 432 433 434
  String toString() => 'AndroidSdk: $directory';
}

class AndroidSdkVersion implements Comparable<AndroidSdkVersion> {
435 436
  AndroidSdkVersion._(
    this.sdk, {
437 438 439 440
    required this.sdkLevel,
    required this.platformName,
    required this.buildToolsVersion,
    required FileSystem fileSystem,
441
  }) : _fileSystem = fileSystem;
442 443

  final AndroidSdk sdk;
444 445
  final int sdkLevel;
  final String platformName;
446
  final Version buildToolsVersion;
447

448 449
  final FileSystem _fileSystem;

450
  String get buildToolsVersionName => buildToolsVersion.toString();
451 452 453

  String get androidJarPath => getPlatformsPath('android.jar');

454 455 456 457 458 459
  /// Return the path to the android application package tool.
  ///
  /// This is used to dump the xml in order to launch built android applications.
  ///
  /// See also:
  ///   * [AndroidApk.fromApk], which depends on this to determine application identifiers.
460 461
  String get aaptPath => getBuildToolsPath('aapt');

462
  List<String> validateSdkWellFormed() {
463 464 465
    final String? existsAndroidJarPath = _exists(androidJarPath);
    if (existsAndroidJarPath != null) {
      return <String>[existsAndroidJarPath];
466
    }
467

468 469 470
    final String? canRunAaptPath = _canRun(aaptPath);
    if (canRunAaptPath != null) {
      return <String>[canRunAaptPath];
471
    }
472 473

    return <String>[];
474 475 476
  }

  String getPlatformsPath(String itemName) {
477
    return sdk.directory.childDirectory('platforms').childDirectory(platformName).childFile(itemName).path;
478 479
  }

480
  String getBuildToolsPath(String binaryName) {
481
    return sdk.directory.childDirectory('build-tools').childDirectory(buildToolsVersionName).childFile(binaryName).path;
482 483
  }

484
  @override
485
  int compareTo(AndroidSdkVersion other) => sdkLevel - other.sdkLevel;
486

487
  @override
488
  String toString() => '[${sdk.directory}, SDK version $sdkLevel, build-tools $buildToolsVersionName]';
489

490
  String? _exists(String path) {
491
    if (!_fileSystem.isFileSync(path)) {
492
      return 'Android SDK file not found: $path.';
493
    }
494
    return null;
495
  }
496

497
  String? _canRun(String path) {
498
    if (!globals.processManager.canRun(path)) {
499
      return 'Android SDK file not found: $path.';
500
    }
501 502
    return null;
  }
503
}