gradle.dart 39.9 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 6
// @dart = 2.8

7
import 'package:crypto/crypto.dart';
8
import 'package:meta/meta.dart';
9
import 'package:process/process.dart';
Dan Field's avatar
Dan Field committed
10
import 'package:xml/xml.dart';
11

12
import '../artifacts.dart';
13
import '../base/analyze_size.dart';
14
import '../base/common.dart';
15
import '../base/file_system.dart';
16
import '../base/io.dart';
17 18
import '../base/logger.dart';
import '../base/process.dart';
19
import '../base/terminal.dart';
20 21 22
import '../base/utils.dart';
import '../build_info.dart';
import '../cache.dart';
23
import '../convert.dart';
24
import '../flutter_manifest.dart';
25
import '../globals.dart' as globals hide logger, printStatus, printTrace, printError, processManager, processUtils, fs, artifacts, flutterUsage;
26
import '../project.dart';
27
import '../reporting/reporting.dart';
28
import 'android_builder.dart';
29
import 'android_studio.dart';
30 31
import 'gradle_errors.dart';
import 'gradle_utils.dart';
32

33 34 35 36 37 38 39 40 41 42
/// The directory where the APK artifact is generated.
Directory getApkDirectory(FlutterProject project) {
  return project.isModule
    ? project.android.buildDirectory
        .childDirectory('host')
        .childDirectory('outputs')
        .childDirectory('apk')
    : project.android.buildDirectory
        .childDirectory('app')
        .childDirectory('outputs')
43
        .childDirectory('flutter-apk');
44
}
45

46 47 48 49 50 51 52 53 54 55 56 57 58
/// The directory where the app bundle artifact is generated.
@visibleForTesting
Directory getBundleDirectory(FlutterProject project) {
  return project.isModule
    ? project.android.buildDirectory
        .childDirectory('host')
        .childDirectory('outputs')
        .childDirectory('bundle')
    : project.android.buildDirectory
        .childDirectory('app')
        .childDirectory('outputs')
        .childDirectory('bundle');
}
59

60 61 62 63 64 65
/// The directory where the repo is generated.
/// Only applicable to AARs.
Directory getRepoDirectory(Directory buildDirectory) {
  return buildDirectory
    .childDirectory('outputs')
    .childDirectory('repo');
66 67
}

68 69 70 71 72 73
/// Returns the name of Gradle task that starts with [prefix].
String _taskFor(String prefix, BuildInfo buildInfo) {
  final String buildType = camelCase(buildInfo.modeName);
  final String productFlavor = buildInfo.flavor ?? '';
  return '$prefix${toTitleCase(productFlavor)}${toTitleCase(buildType)}';
}
74

75 76 77 78
/// Returns the task to build an APK.
@visibleForTesting
String getAssembleTaskFor(BuildInfo buildInfo) {
  return _taskFor('assemble', buildInfo);
79
}
80

81 82 83 84 85
/// Returns the task to build an AAB.
@visibleForTesting
String getBundleTaskFor(BuildInfo buildInfo) {
  return _taskFor('bundle', buildInfo);
}
86

87 88 89 90 91
/// Returns the task to build an AAR.
@visibleForTesting
String getAarTaskFor(BuildInfo buildInfo) {
  return _taskFor('assembleAar', buildInfo);
}
92

93 94 95 96 97
/// Returns the output APK file names for a given [AndroidBuildInfo].
///
/// For example, when [splitPerAbi] is true, multiple APKs are created.
Iterable<String> _apkFilesFor(AndroidBuildInfo androidBuildInfo) {
  final String buildType = camelCase(androidBuildInfo.buildInfo.modeName);
98
  final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? '';
99 100 101 102 103 104 105 106 107
  final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor';
  if (androidBuildInfo.splitPerAbi) {
    return androidBuildInfo.targetArchs.map<String>((AndroidArch arch) {
      final String abi = getNameForAndroidArch(arch);
      return 'app$flavorString-$abi-$buildType.apk';
    });
  }
  return <String>['app$flavorString-$buildType.apk'];
}
108

109 110 111
/// Tries to create `settings_aar.gradle` in an app project by removing the subprojects
/// from the existing `settings.gradle` file. This operation will fail if the existing
/// `settings.gradle` file has local edits.
112
@visibleForTesting
113
void createSettingsAarGradle(Directory androidDirectory, Logger logger) {
114
  final FileSystem fileSystem = androidDirectory.fileSystem;
115 116 117 118 119 120 121 122 123 124
  final File newSettingsFile = androidDirectory.childFile('settings_aar.gradle');
  if (newSettingsFile.existsSync()) {
    return;
  }
  final File currentSettingsFile = androidDirectory.childFile('settings.gradle');
  if (!currentSettingsFile.existsSync()) {
    return;
  }
  final String currentFileContent = currentSettingsFile.readAsStringSync();

125
  final String newSettingsRelativeFile = fileSystem.path.relative(newSettingsFile.path);
126
  final Status status = logger.startProgress('✏️  Creating `$newSettingsRelativeFile`...');
127

128 129
  final String flutterRoot = fileSystem.path.absolute(Cache.flutterRoot);
  final File legacySettingsDotGradleFiles = fileSystem.file(fileSystem.path.join(flutterRoot, 'packages','flutter_tools',
130 131
      'gradle', 'settings.gradle.legacy_versions'));
  assert(legacySettingsDotGradleFiles.existsSync());
132
  final String settingsAarContent = fileSystem.file(fileSystem.path.join(flutterRoot, 'packages','flutter_tools',
133 134 135
      'gradle', 'settings_aar.gradle.tmpl')).readAsStringSync();

  // Get the `settings.gradle` content variants that should be patched.
136
  final List<String> existingVariants = legacySettingsDotGradleFiles.readAsStringSync().split(';EOF');
137 138 139
  existingVariants.add(settingsAarContent);

  bool exactMatch = false;
140
  for (final String fileContentVariant in existingVariants) {
141 142 143 144 145 146 147
    if (currentFileContent.trim() == fileContentVariant.trim()) {
      exactMatch = true;
      break;
    }
  }
  if (!exactMatch) {
    status.cancel();
148
    logger.printStatus('$warningMark Flutter tried to create the file `$newSettingsRelativeFile`, but failed.');
149
    // Print how to manually update the file.
150
    logger.printStatus(fileSystem.file(fileSystem.path.join(flutterRoot, 'packages','flutter_tools',
151 152 153 154 155 156
        'gradle', 'manual_migration_settings.gradle.md')).readAsStringSync());
    throwToolExit('Please create the file and run this command again.');
  }
  // Copy the new file.
  newSettingsFile.writeAsStringSync(settingsAarContent);
  status.stop();
157
  logger.printStatus('$successMark `$newSettingsRelativeFile` created successfully.');
158 159
}

160 161
/// An implementation of the [AndroidBuilder] that delegates to gradle.
class AndroidGradleBuilder implements AndroidBuilder {
162 163
  AndroidGradleBuilder({
    @required Logger logger,
164 165
    @required ProcessManager processManager,
    @required FileSystem fileSystem,
166
    @required Artifacts artifacts,
167
    @required Usage usage,
168 169
  }) : _logger = logger,
       _fileSystem = fileSystem,
170
       _artifacts = artifacts,
171
       _usage = usage,
172
       _processUtils = ProcessUtils(logger: logger, processManager: processManager);
173 174

  final Logger _logger;
175 176
  final ProcessUtils _processUtils;
  final FileSystem _fileSystem;
177
  final Artifacts _artifacts;
178
  final Usage _usage;
179

180 181 182 183 184 185 186 187 188 189 190
  /// Builds the AAR and POM files for the current Flutter module or plugin.
  @override
  Future<void> buildAar({
    @required FlutterProject project,
    @required Set<AndroidBuildInfo> androidBuildInfo,
    @required String target,
    @required String outputDirectoryPath,
    @required String buildNumber,
  }) async {
    try {
      Directory outputDirectory =
191
        _fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory);
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
      if (project.isModule) {
        // Module projects artifacts are located in `build/host`.
        outputDirectory = outputDirectory.childDirectory('host');
      }
      for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) {
        await buildGradleAar(
          project: project,
          androidBuildInfo: androidBuildInfo,
          target: target,
          outputDirectory: outputDirectory,
          buildNumber: buildNumber,
        );
      }
      printHowToConsumeAar(
        buildModes: androidBuildInfo
          .map<String>((AndroidBuildInfo androidBuildInfo) {
            return androidBuildInfo.buildInfo.modeName;
          }).toSet(),
        androidPackage: project.manifest.androidPackage,
        repoDirectory: getRepoDirectory(outputDirectory),
        buildNumber: buildNumber,
213
        logger: _logger,
214
        fileSystem: _fileSystem,
215 216 217 218
      );
    } finally {
      globals.androidSdk?.reinitialize();
    }
219
  }
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

  /// Builds the APK.
  @override
  Future<void> buildApk({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
  }) async {
    try {
      await buildGradleApp(
        project: project,
        androidBuildInfo: androidBuildInfo,
        target: target,
        isBuildingBundle: false,
        localGradleErrors: gradleErrors,
      );
    } finally {
      globals.androidSdk?.reinitialize();
    }
Emmanuel Garcia's avatar
Emmanuel Garcia committed
239
  }
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

  /// Builds the App Bundle.
  @override
  Future<void> buildAab({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
  }) async {
    try {
      await buildGradleApp(
        project: project,
        androidBuildInfo: androidBuildInfo,
        target: target,
        isBuildingBundle: true,
        localGradleErrors: gradleErrors,
      );
    } finally {
      globals.androidSdk?.reinitialize();
    }
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
  /// Builds an app.
  ///
  /// * [project] is typically [FlutterProject.current()].
  /// * [androidBuildInfo] is the build configuration.
  /// * [target] is the target dart entry point. Typically, `lib/main.dart`.
  /// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`,
  ///   otherwise the output artifact is an `*.apk`.
  /// * The plugins are built as AARs if [shouldBuildPluginAsAar] is `true`. This isn't set by default
  ///   because it makes the build slower proportional to the number of plugins.
  /// * [retries] is the max number of build retries in case one of the [GradleHandledError] handler
  ///   returns [GradleBuildStatus.retry] or [GradleBuildStatus.retryWithAarPlugins].
  Future<void> buildGradleApp({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
    @required bool isBuildingBundle,
    @required List<GradleHandledError> localGradleErrors,
    bool shouldBuildPluginAsAar = false,
    int retries = 1,
  }) async {
    assert(project != null);
    assert(androidBuildInfo != null);
    assert(target != null);
    assert(isBuildingBundle != null);
    assert(localGradleErrors != null);
    assert(globals.androidSdk != null);

288
    if (!project.android.isSupportedVersion) {
289
      _exitWithUnsupportedProjectMessage(_usage);
290 291 292 293 294
    }
    final Directory buildDirectory = project.android.buildDirectory;

    final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot);
    if (usesAndroidX) {
295
      BuildEvent('app-using-android-x', flutterUsage: _usage).send();
296
    } else if (!usesAndroidX) {
297
      BuildEvent('app-not-using-android-x', flutterUsage: _usage).send();
298 299
      _logger.printStatus("$warningMark Your app isn't using AndroidX.", emphasis: true);
      _logger.printStatus(
300 301 302 303 304 305 306 307 308 309 310
        'To avoid potential build failures, you can quickly migrate your app '
            'by following the steps on https://goo.gl/CP92wY .',
        indent: 4,
      );
    }
    // The default Gradle script reads the version name and number
    // from the local.properties file.
    updateLocalProperties(project: project, buildInfo: androidBuildInfo.buildInfo);

    if (shouldBuildPluginAsAar) {
      // Create a settings.gradle that doesn't import the plugins as subprojects.
311
      createSettingsAarGradle(project.android.hostAppGradleRoot, _logger);
312 313 314 315 316 317
      await buildPluginsAsAar(
        project,
        androidBuildInfo,
        buildDirectory: buildDirectory.childDirectory('app'),
      );
    }
318

319 320 321 322
    final BuildInfo buildInfo = androidBuildInfo.buildInfo;
    final String assembleTask = isBuildingBundle
        ? getBundleTaskFor(buildInfo)
        : getAssembleTaskFor(buildInfo);
323

324
    final Status status = _logger.startProgress(
325 326
      "Running Gradle task '$assembleTask'...",
      multilineOutput: true,
327
    );
328

329
    final List<String> command = <String>[
330
      globals.gradleUtils.getExecutable(project),
331
    ];
332
    if (_logger.isVerbose) {
333 334 335 336 337 338 339
      command.add('-Pverbose=true');
    } else {
      command.add('-q');
    }
    if (!buildInfo.androidGradleDaemon) {
      command.add('--no-daemon');
    }
340 341
    if (_artifacts is LocalEngineArtifacts) {
      final LocalEngineArtifacts localEngineArtifacts = _artifacts as LocalEngineArtifacts;
342 343 344
      final Directory localEngineRepo = _getLocalEngineRepo(
        engineOutPath: localEngineArtifacts.engineOutPath,
        androidBuildInfo: androidBuildInfo,
345
        fileSystem: _fileSystem,
346
      );
347
      _logger.printTrace(
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
          'Using local engine: ${localEngineArtifacts.engineOutPath}\n'
              'Local Maven repo: ${localEngineRepo.path}'
      );
      command.add('-Plocal-engine-repo=${localEngineRepo.path}');
      command.add('-Plocal-engine-build-mode=${buildInfo.modeName}');
      command.add('-Plocal-engine-out=${localEngineArtifacts.engineOutPath}');
      command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath(
          localEngineArtifacts.engineOutPath)}');
    } else if (androidBuildInfo.targetArchs.isNotEmpty) {
      final String targetPlatforms = androidBuildInfo
          .targetArchs
          .map(getPlatformNameForAndroidArch).join(',');
      command.add('-Ptarget-platform=$targetPlatforms');
    }
    if (target != null) {
      command.add('-Ptarget=$target');
    }
    command.addAll(androidBuildInfo.buildInfo.toGradleConfig());

    if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) {
      command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}');
    }
    if (buildInfo.fileSystemScheme != null) {
      command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}');
    }
    if (androidBuildInfo.splitPerAbi) {
      command.add('-Psplit-per-abi=true');
    }
    if (shouldBuildPluginAsAar) {
      // Pass a system flag instead of a project flag, so this flag can be
      // read from include_flutter.groovy.
      command.add('-Dbuild-plugins-as-aars=true');
      // Don't use settings.gradle from the current project since it includes the plugins as subprojects.
      command.add('--settings-file=settings_aar.gradle');
    }
    if (androidBuildInfo.fastStart) {
      command.add('-Pfast-start=true');
    }
    command.add(assembleTask);

    GradleHandledError detectedGradleError;
    String detectedGradleErrorLine;
    String consumeLog(String line) {
      // This message was removed from first-party plugins,
      // but older plugin versions still display this message.
      if (androidXPluginWarningRegex.hasMatch(line)) {
        // Don't pipe.
        return null;
      }
      if (detectedGradleError != null) {
        // Pipe stdout/stderr from Gradle.
        return line;
      }
      for (final GradleHandledError gradleError in localGradleErrors) {
        if (gradleError.test(line)) {
          detectedGradleErrorLine = line;
          detectedGradleError = gradleError;
          // The first error match wins.
          break;
        }
      }
409 410 411
      // Pipe stdout/stderr from Gradle.
      return line;
    }
412 413 414 415 416

    final Stopwatch sw = Stopwatch()
      ..start();
    int exitCode = 1;
    try {
417
      exitCode = await _processUtils.stream(
418 419 420
        command,
        workingDirectory: project.android.hostAppGradleRoot.path,
        allowReentrantFlutter: true,
421 422 423 424
        environment: <String, String>{
          if (javaPath != null)
            'JAVA_HOME': javaPath,
        },
425 426 427 428 429 430 431 432
        mapFunction: consumeLog,
      );
    } on ProcessException catch (exception) {
      consumeLog(exception.toString());
      // Rethrow the exception if the error isn't handled by any of the
      // `localGradleErrors`.
      if (detectedGradleError == null) {
        rethrow;
433
      }
434 435
    } finally {
      status.stop();
436 437
    }

438
    _usage.sendTiming('build', 'gradle', sw.elapsed);
439 440 441

    if (exitCode != 0) {
      if (detectedGradleError == null) {
442
        BuildEvent('gradle-unknown-failure', flutterUsage: _usage).send();
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
        throwToolExit(
          'Gradle task $assembleTask failed with exit code $exitCode',
          exitCode: exitCode,
        );
      } else {
        final GradleBuildStatus status = await detectedGradleError.handler(
          line: detectedGradleErrorLine,
          project: project,
          usesAndroidX: usesAndroidX,
          shouldBuildPluginAsAar: shouldBuildPluginAsAar,
        );

        if (retries >= 1) {
          final String successEventLabel = 'gradle-${detectedGradleError.eventLabel}-success';
          switch (status) {
            case GradleBuildStatus.retry:
              await buildGradleApp(
                project: project,
                androidBuildInfo: androidBuildInfo,
                target: target,
                isBuildingBundle: isBuildingBundle,
                localGradleErrors: localGradleErrors,
                shouldBuildPluginAsAar: shouldBuildPluginAsAar,
                retries: retries - 1,
              );
468
              BuildEvent(successEventLabel, flutterUsage: _usage).send();
469 470 471 472 473 474 475 476 477 478 479
              return;
            case GradleBuildStatus.retryWithAarPlugins:
              await buildGradleApp(
                project: project,
                androidBuildInfo: androidBuildInfo,
                target: target,
                isBuildingBundle: isBuildingBundle,
                localGradleErrors: localGradleErrors,
                shouldBuildPluginAsAar: true,
                retries: retries - 1,
              );
480
              BuildEvent(successEventLabel, flutterUsage: _usage).send();
481 482 483 484 485
              return;
            case GradleBuildStatus.exit:
            // noop.
          }
        }
486
        BuildEvent('gradle-${detectedGradleError.eventLabel}-failure', flutterUsage: _usage).send();
487 488 489 490 491 492
        throwToolExit(
          'Gradle task $assembleTask failed with exit code $exitCode',
          exitCode: exitCode,
        );
      }
    }
493

494
    if (isBuildingBundle) {
495
      final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage);
496 497 498
      final String appSize = (buildInfo.mode == BuildMode.debug)
          ? '' // Don't display the size when building a debug variant.
          : ' (${getSizeAsMB(bundleFile.lengthSync())})';
499

500 501 502 503
      if (buildInfo.codeSizeDirectory != null) {
        await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo);
      }

504
      _logger.printStatus(
505
        '$successMark Built ${_fileSystem.path.relative(bundleFile.path)}$appSize.',
506
        color: TerminalColor.green,
507
      );
508 509 510 511
      return;
    }
    // Gradle produced an APK.
    final Iterable<String> apkFilesPaths = project.isModule
512
        ? findApkFilesModule(project, androidBuildInfo, _logger, _usage)
513 514 515 516 517
        : listApkPaths(androidBuildInfo);
    final Directory apkDirectory = getApkDirectory(project);
    final File apkFile = apkDirectory.childFile(apkFilesPaths.first);
    if (!apkFile.existsSync()) {
      _exitWithExpectedFileNotFound(
518
        project: project,
519
        fileExtension: '.apk',
520
        logger: _logger,
521
        usage: _usage,
522
      );
523
    }
524

525 526 527 528 529
    // Copy the first APK to app.apk, so `flutter run` can find it.
    // TODO(egarciad): Handle multiple APKs.
    apkFile.copySync(apkDirectory
        .childFile('app.apk')
        .path);
530
    _logger.printTrace('calculateSha: $apkDirectory/app.apk');
531

532 533
    final File apkShaFile = apkDirectory.childFile('app.apk.sha1');
    apkShaFile.writeAsStringSync(_calculateSha(apkFile));
534

535 536 537
    final String appSize = (buildInfo.mode == BuildMode.debug)
        ? '' // Don't display the size when building a debug variant.
        : ' (${getSizeAsMB(apkFile.lengthSync())})';
538
    _logger.printStatus(
539
      '$successMark Built ${_fileSystem.path.relative(apkFile.path)}$appSize.',
540 541
      color: TerminalColor.green,
    );
542

543 544 545
    if (buildInfo.codeSizeDirectory != null) {
      await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo);
    }
546 547
  }

548 549 550 551
  Future<void> _performCodeSizeAnalysis(String kind,
      File zipFile,
      AndroidBuildInfo androidBuildInfo,) async {
    final SizeAnalyzer sizeAnalyzer = SizeAnalyzer(
552
      fileSystem: _fileSystem,
553
      logger: _logger,
554
      flutterUsage: _usage,
555 556 557
    );
    final String archName = getNameForAndroidArch(androidBuildInfo.targetArchs.single);
    final BuildInfo buildInfo = androidBuildInfo.buildInfo;
558
    final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory)
559
        .childFile('snapshot.$archName.json');
560
    final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory)
561 562 563 564 565 566 567 568
        .childFile('trace.$archName.json');
    final Map<String, Object> output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot(
      zipFile: zipFile,
      aotSnapshot: aotSnapshot,
      precompilerTrace: precompilerTrace,
      kind: kind,
    );
    final File outputFile = globals.fsUtils.getUniqueFile(
569 570 571
      _fileSystem
        .directory(globals.fsUtils.homeDirPath)
        .childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json',
572 573 574
    )
      ..writeAsStringSync(jsonEncode(output));
    // This message is used as a sentinel in analyze_apk_size_test.dart
575
    _logger.printStatus(
576 577
      'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}',
    );
578

579 580 581 582 583
    // DevTools expects a file path relative to the .flutter-devtools/ dir.
    final String relativeAppSizePath = outputFile.path
        .split('.flutter-devtools/')
        .last
        .trim();
584
    _logger.printStatus(
585 586 587
        '\nTo analyze your app size in Dart DevTools, run the following command:\n'
            'flutter pub global activate devtools; flutter pub global run devtools '
            '--appSizeBase=$relativeAppSizePath'
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
  /// Builds AAR and POM files.
  ///
  /// * [project] is typically [FlutterProject.current()].
  /// * [androidBuildInfo] is the build configuration.
  /// * [outputDir] is the destination of the artifacts,
  /// * [buildNumber] is the build number of the output aar,
  Future<void> buildGradleAar({
    @required FlutterProject project,
    @required AndroidBuildInfo androidBuildInfo,
    @required String target,
    @required Directory outputDirectory,
    @required String buildNumber,
  }) async {
    assert(project != null);
    assert(target != null);
    assert(androidBuildInfo != null);
    assert(outputDirectory != null);
    assert(globals.androidSdk != null);

    final FlutterManifest manifest = project.manifest;
    if (!manifest.isModule && !manifest.isPlugin) {
      throwToolExit('AARs can only be built for plugin or module projects.');
    }

    final BuildInfo buildInfo = androidBuildInfo.buildInfo;
    final String aarTask = getAarTaskFor(buildInfo);
617
    final Status status = _logger.startProgress(
618 619
      "Running Gradle task '$aarTask'...",
      multilineOutput: true,
620
    );
621

622 623
    final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot);
    final String initScript = _fileSystem.path.join(
624 625 626 627 628
      flutterRoot,
      'packages',
      'flutter_tools',
      'gradle',
      'aar_init_script.gradle',
629
    );
630
    final List<String> command = <String>[
631
      globals.gradleUtils.getExecutable(project),
632 633 634 635 636 637
      '-I=$initScript',
      '-Pflutter-root=$flutterRoot',
      '-Poutput-dir=${outputDirectory.path}',
      '-Pis-plugin=${manifest.isPlugin}',
      '-PbuildNumber=$buildNumber'
    ];
638
    if (_logger.isVerbose) {
639 640 641 642 643 644 645
      command.add('-Pverbose=true');
    } else {
      command.add('-q');
    }
    if (!buildInfo.androidGradleDaemon) {
      command.add('--no-daemon');
    }
646

647 648 649 650 651
    if (target != null && target.isNotEmpty) {
      command.add('-Ptarget=$target');
    }
    command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
    if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) {
652
      _logger.printStatus(
653 654
        'Dart obfuscation is not supported in ${toTitleCase(buildInfo.friendlyModeName)}'
            ' mode, building as un-obfuscated.',
655
      );
656 657
    }

658 659
    if (_artifacts is LocalEngineArtifacts) {
      final LocalEngineArtifacts localEngineArtifacts = _artifacts as LocalEngineArtifacts;
660 661 662
      final Directory localEngineRepo = _getLocalEngineRepo(
        engineOutPath: localEngineArtifacts.engineOutPath,
        androidBuildInfo: androidBuildInfo,
663
        fileSystem: _fileSystem,
664
      );
665 666 667
      _logger.printTrace(
        'Using local engine: ${localEngineArtifacts.engineOutPath}\n'
        'Local Maven repo: ${localEngineRepo.path}'
668
      );
669 670 671 672 673 674
      command.add('-Plocal-engine-repo=${localEngineRepo.path}');
      command.add('-Plocal-engine-build-mode=${buildInfo.modeName}');
      command.add('-Plocal-engine-out=${localEngineArtifacts.engineOutPath}');

      // Copy the local engine repo in the output directory.
      try {
675
        copyDirectory(
676 677 678
          localEngineRepo,
          getRepoDirectory(outputDirectory),
        );
679
      } on FileSystemException catch (error, st) {
680 681
        throwToolExit(
            'Failed to copy the local engine ${localEngineRepo.path} repo '
682
                'in ${outputDirectory.path}: $error, $st'
683 684 685 686 687 688 689 690
        );
      }
      command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath(
          localEngineArtifacts.engineOutPath)}');
    } else if (androidBuildInfo.targetArchs.isNotEmpty) {
      final String targetPlatforms = androidBuildInfo.targetArchs
          .map(getPlatformNameForAndroidArch).join(',');
      command.add('-Ptarget-platform=$targetPlatforms');
691
    }
692

693
    command.add(aarTask);
694

695 696 697 698
    final Stopwatch sw = Stopwatch()
      ..start();
    RunResult result;
    try {
699
      result = await _processUtils.run(
700 701 702
        command,
        workingDirectory: project.android.hostAppGradleRoot.path,
        allowReentrantFlutter: true,
703 704 705 706
        environment: <String, String>{
          if (javaPath != null)
            'JAVA_HOME': javaPath,
        },
707 708 709 710
      );
    } finally {
      status.stop();
    }
711
    _usage.sendTiming('build', 'gradle-aar', sw.elapsed);
712 713

    if (result.exitCode != 0) {
714 715
      _logger.printStatus(result.stdout, wrap: false);
      _logger.printError(result.stderr, wrap: false);
716 717 718 719 720 721 722
      throwToolExit(
        'Gradle task $aarTask failed with exit code ${result.exitCode}.',
        exitCode: result.exitCode,
      );
    }
    final Directory repoDirectory = getRepoDirectory(outputDirectory);
    if (!repoDirectory.existsSync()) {
723 724
      _logger.printStatus(result.stdout, wrap: false);
      _logger.printError(result.stderr, wrap: false);
725 726 727 728 729
      throwToolExit(
        'Gradle task $aarTask failed to produce $repoDirectory.',
        exitCode: exitCode,
      );
    }
730
    _logger.printStatus(
731
      '$successMark Built ${_fileSystem.path.relative(repoDirectory.path)}.',
732
      color: TerminalColor.green,
733
    );
734
  }
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752

  /// Builds the plugins as AARs.
  @visibleForTesting
  Future<void> buildPluginsAsAar(
    FlutterProject flutterProject,
    AndroidBuildInfo androidBuildInfo, {
    Directory buildDirectory,
  }) async {
    final File flutterPluginFile = flutterProject.flutterPluginsFile;
    if (!flutterPluginFile.existsSync()) {
      return;
    }
    final List<String> plugins = flutterPluginFile.readAsStringSync().split('\n');
    for (final String plugin in plugins) {
      final List<String> pluginParts = plugin.split('=');
      if (pluginParts.length != 2) {
        continue;
      }
753
      final Directory pluginDirectory = _fileSystem.directory(pluginParts.last);
754 755 756 757 758
      assert(pluginDirectory.existsSync());

      final String pluginName = pluginParts.first;
      final File buildGradleFile = pluginDirectory.childDirectory('android').childFile('build.gradle');
      if (!buildGradleFile.existsSync()) {
759
        _logger.printTrace("Skipping plugin $pluginName since it doesn't have a android/build.gradle file");
760 761
        continue;
      }
762
      _logger.printStatus('Building plugin $pluginName...');
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
      try {
        await buildGradleAar(
          project: FlutterProject.fromDirectory(pluginDirectory),
          androidBuildInfo: AndroidBuildInfo(
            BuildInfo(
              BuildMode.release, // Plugins are built as release.
              null, // Plugins don't define flavors.
              treeShakeIcons: androidBuildInfo.buildInfo.treeShakeIcons,
              packagesPath: androidBuildInfo.buildInfo.packagesPath,
            ),
          ),
          target: '',
          outputDirectory: buildDirectory,
          buildNumber: '1.0'
        );
      } on ToolExit {
        // Log the entire plugin entry in `.flutter-plugins` since it
        // includes the plugin name and the version.
781
        BuildEvent('gradle-plugin-aar-failure', eventError: plugin, flutterUsage: _usage).send();
782 783 784
        throwToolExit('The plugin $pluginName could not be built due to the issue above.');
      }
    }
785
  }
786 787 788
}

/// Prints how to consume the AAR from a host app.
789 790
void printHowToConsumeAar({
  @required Set<String> buildModes,
791
  @required String androidPackage,
792
  @required Directory repoDirectory,
793 794
  @required Logger logger,
  @required FileSystem fileSystem,
795
  String buildNumber,
796
}) {
797
  assert(buildModes != null && buildModes.isNotEmpty);
798
  assert(androidPackage != null);
799
  assert(repoDirectory != null);
800
  buildNumber ??= '1.0';
801

802 803 804
  logger.printStatus('\nConsuming the Module', emphasis: true);
  logger.printStatus('''
  1. Open ${fileSystem.path.join('<host>', 'app', 'build.gradle')}
805 806
  2. Ensure you have the repositories configured, otherwise add them:

807
      String storageUrl = System.env.FLUTTER_STORAGE_BASE_URL ?: "https://storage.googleapis.com"
808 809
      repositories {
        maven {
810
            url '${repoDirectory.path}'
811 812
        }
        maven {
813
            url "\$storageUrl/download.flutter.io"
814 815 816
        }
      }

817
  3. Make the host app depend on the Flutter module:
818

819 820
    dependencies {''');

821
  for (final String buildMode in buildModes) {
822
    logger.printStatus("""
823
      ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'""");
824 825
  }

826
  logger.printStatus('''
827 828 829 830
    }
''');

  if (buildModes.contains('profile')) {
831
    logger.printStatus('''
832 833 834 835 836 837 838 839

  4. Add the `profile` build type:

    android {
      buildTypes {
        profile {
          initWith debug
        }
840
      }
841 842 843
    }
''');
  }
844

845
  logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar');
846 847
}

848 849
String _hex(List<int> bytes) {
  final StringBuffer result = StringBuffer();
850
  for (final int part in bytes) {
851
    result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
852
  }
853 854 855 856 857
  return result.toString();
}

String _calculateSha(File file) {
  final List<int> bytes = file.readAsBytesSync();
858
  return _hex(sha1.convert(bytes).bytes);
859 860
}

861 862
void _exitWithUnsupportedProjectMessage(Usage usage) {
  BuildEvent('unsupported-project', eventError: 'gradle-plugin', flutterUsage: usage).send();
863 864 865 866 867
  throwToolExit(
    '$warningMark Your app is using an unsupported Gradle project. '
    'To fix this problem, create a new project by running `flutter create -t app <app-directory>` '
    'and then move the dart code, assets and pubspec.yaml to the new project.',
  );
868 869
}

870 871 872 873 874 875 876 877 878 879 880
/// Returns [true] if the current app uses AndroidX.
// TODO(egarciad): https://github.com/flutter/flutter/issues/40800
// Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`.
bool isAppUsingAndroidX(Directory androidDirectory) {
  final File properties = androidDirectory.childFile('gradle.properties');
  if (!properties.existsSync()) {
    return false;
  }
  return properties.readAsStringSync().contains('android.useAndroidX=true');
}

881
/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].
882
@visibleForTesting
883
Iterable<String> findApkFilesModule(
884
  FlutterProject project,
885
  AndroidBuildInfo androidBuildInfo,
886
  Logger logger,
887
  Usage usage,
888
) {
889 890
  final Iterable<String> apkFileNames = _apkFilesFor(androidBuildInfo);
  final Directory apkDirectory = getApkDirectory(project);
891
  final Iterable<File> apks = apkFileNames.expand<File>((String apkFileName) {
892
    File apkFile = apkDirectory.childFile(apkFileName);
893
    if (apkFile.existsSync()) {
894
      return <File>[apkFile];
895
    }
896 897
    final BuildInfo buildInfo = androidBuildInfo.buildInfo;
    final String modeName = camelCase(buildInfo.modeName);
898 899 900
    apkFile = apkDirectory
      .childDirectory(modeName)
      .childFile(apkFileName);
901
    if (apkFile.existsSync()) {
902
      return <File>[apkFile];
903
    }
904 905
    if (buildInfo.flavor != null) {
      // Android Studio Gradle plugin v3 adds flavor to path.
906 907 908 909
      apkFile = apkDirectory
        .childDirectory(buildInfo.flavor)
        .childDirectory(modeName)
        .childFile(apkFileName);
910
      if (apkFile.existsSync()) {
911
        return <File>[apkFile];
912
      }
913
    }
914
    return const <File>[];
915
  });
916 917 918 919
  if (apks.isEmpty) {
    _exitWithExpectedFileNotFound(
      project: project,
      fileExtension: '.apk',
920
      logger: logger,
921
      usage: usage,
922 923
    );
  }
924 925 926 927 928 929
  return apks.map((File file) => file.path);
}

/// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo].
///
/// The flutter.gradle plugin will copy APK outputs into:
930
/// `$buildDir/app/outputs/flutter-apk/app-<abi>-<flavor-flag>-<build-mode-flag>.apk`
931 932 933 934 935 936 937
@visibleForTesting
Iterable<String> listApkPaths(
  AndroidBuildInfo androidBuildInfo,
) {
  final String buildType = camelCase(androidBuildInfo.buildInfo.modeName);
  final List<String> apkPartialName = <String>[
    if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false)
938
      androidBuildInfo.buildInfo.lowerCasedFlavor,
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
    '$buildType.apk',
  ];
  if (androidBuildInfo.splitPerAbi) {
    return <String>[
      for (AndroidArch androidArch in androidBuildInfo.targetArchs)
        <String>[
          'app',
          getNameForAndroidArch(androidArch),
          ...apkPartialName
        ].join('-')
    ];
  }
  return <String>[
    <String>[
      'app',
      ...apkPartialName,
    ].join('-')
  ];
957
}
958

959
@visibleForTesting
960
File findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage) {
961
  final List<File> fileCandidates = <File>[
962
    getBundleDirectory(project)
963 964
      .childDirectory(camelCase(buildInfo.modeName))
      .childFile('app.aab'),
965
    getBundleDirectory(project)
966 967 968 969 970 971 972 973
      .childDirectory(camelCase(buildInfo.modeName))
      .childFile('app-${buildInfo.modeName}.aab'),
  ];
  if (buildInfo.flavor != null) {
    // The Android Gradle plugin 3.0.0 adds the flavor name to the path.
    // For example: In release mode, if the flavor name is `foo_bar`, then
    // the directory name is `foo_barRelease`.
    fileCandidates.add(
974
      getBundleDirectory(project)
975
        .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_' + buildInfo.modeName)}')
976 977 978 979 980 981
        .childFile('app.aab'));

    // The Android Gradle plugin 3.5.0 adds the flavor name to file name.
    // For example: In release mode, if the flavor name is `foo_bar`, then
    // the file name name is `app-foo_bar-release.aab`.
    fileCandidates.add(
982
      getBundleDirectory(project)
983 984
        .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_' + buildInfo.modeName)}')
        .childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab'));
985 986 987 988 989
  }
  for (final File bundleFile in fileCandidates) {
    if (bundleFile.existsSync()) {
      return bundleFile;
    }
990
  }
991 992 993
  _exitWithExpectedFileNotFound(
    project: project,
    fileExtension: '.aab',
994
    logger: logger,
995
    usage: usage,
996
  );
997 998
  return null;
}
999 1000 1001 1002 1003

/// Throws a [ToolExit] exception and logs the event.
void _exitWithExpectedFileNotFound({
  @required FlutterProject project,
  @required String fileExtension,
1004
  @required Logger logger,
1005
  @required Usage usage,
1006 1007 1008 1009 1010
}) {
  assert(project != null);
  assert(fileExtension != null);

  final String androidGradlePluginVersion =
1011
  getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger);
1012 1013
  BuildEvent('gradle-expected-file-not-found',
    settings:
1014 1015
    'androidGradlePluginVersion: $androidGradlePluginVersion, '
      'fileExtension: $fileExtension',
1016
    flutterUsage: usage,
1017
  ).send();
1018 1019
  throwToolExit(
    'Gradle build failed to produce an $fileExtension file. '
1020 1021
    "It's likely that this file was generated under ${project.android.buildDirectory.path}, "
    "but the tool couldn't find it."
1022 1023
  );
}
1024

1025 1026
void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) {
  final File targetFile = fileSystem.file(targetPath);
1027
  if (!targetFile.existsSync()) {
1028
    throwToolExit("The file $targetPath wasn't found in the local engine out directory.");
1029
  }
1030
  final File linkFile = fileSystem.file(linkPath);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
  final Link symlink = linkFile.parent.childLink(linkFile.basename);
  try {
    symlink.createSync(targetPath, recursive: true);
  } on FileSystemException catch (exception) {
    throwToolExit(
      'Failed to create the symlink $linkPath->$targetPath: $exception'
    );
  }
}

1041 1042
String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) {
  final File pomFile = fileSystem.file(pomPath);
1043
  if (!pomFile.existsSync()) {
1044
    throwToolExit("The file $pomPath wasn't found in the local engine out directory.");
1045
  }
Dan Field's avatar
Dan Field committed
1046
  XmlDocument document;
1047
  try {
Dan Field's avatar
Dan Field committed
1048 1049
    document = XmlDocument.parse(pomFile.readAsStringSync());
  } on XmlParserException {
1050 1051 1052 1053 1054
    throwToolExit(
      'Error parsing $pomPath. Please ensure that this is a valid XML document.'
    );
  } on FileSystemException {
    throwToolExit(
1055
      'Error reading $pomPath. Please ensure that you have read permission to this '
1056 1057
      'file and try again.');
  }
Dan Field's avatar
Dan Field committed
1058
  final Iterable<XmlElement> project = document.findElements('project');
1059
  assert(project.isNotEmpty);
Dan Field's avatar
Dan Field committed
1060
  for (final XmlElement versionElement in document.findAllElements('version')) {
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    if (versionElement.parent == project.first) {
      return versionElement.text;
    }
  }
  throwToolExit('Error while parsing the <version> element from $pomPath');
  return null;
}

/// Returns the local Maven repository for a local engine build.
/// For example, if the engine is built locally at <home>/engine/src/out/android_release_unopt
/// This method generates symlinks in the temp directory to the engine artifacts
/// following the convention specified on https://maven.apache.org/pom.html#Repositories
Directory _getLocalEngineRepo({
  @required String engineOutPath,
  @required AndroidBuildInfo androidBuildInfo,
1076
  @required FileSystem fileSystem,
1077 1078 1079 1080
}) {
  assert(engineOutPath != null);
  assert(androidBuildInfo != null);

1081
  final String abi = _getAbiByLocalEnginePath(engineOutPath);
1082
  final Directory localEngineRepo = fileSystem.systemTempDirectory
1083 1084 1085
    .createTempSync('flutter_tool_local_engine_repo.');
  final String buildMode = androidBuildInfo.buildInfo.modeName;
  final String artifactVersion = _getLocalArtifactVersion(
1086
    fileSystem.path.join(
1087 1088
      engineOutPath,
      'flutter_embedding_$buildMode.pom',
1089 1090
    ),
    fileSystem,
1091
  );
1092
  for (final String artifact in const <String>['pom', 'jar']) {
1093 1094
    // The Android embedding artifacts.
    _createSymlink(
1095
      fileSystem.path.join(
1096 1097 1098
        engineOutPath,
        'flutter_embedding_$buildMode.$artifact',
      ),
1099
      fileSystem.path.join(
1100 1101 1102 1103 1104 1105 1106
        localEngineRepo.path,
        'io',
        'flutter',
        'flutter_embedding_$buildMode',
        artifactVersion,
        'flutter_embedding_$buildMode-$artifactVersion.$artifact',
      ),
1107
      fileSystem,
1108 1109 1110
    );
    // The engine artifacts (libflutter.so).
    _createSymlink(
1111
      fileSystem.path.join(
1112 1113 1114
        engineOutPath,
        '${abi}_$buildMode.$artifact',
      ),
1115
      fileSystem.path.join(
1116 1117 1118 1119 1120 1121 1122
        localEngineRepo.path,
        'io',
        'flutter',
        '${abi}_$buildMode',
        artifactVersion,
        '${abi}_$buildMode-$artifactVersion.$artifact',
      ),
1123
      fileSystem,
1124 1125
    );
  }
1126 1127
  for (final String artifact in <String>['flutter_embedding_$buildMode', '${abi}_$buildMode']) {
    _createSymlink(
1128
      fileSystem.path.join(
1129 1130 1131
        engineOutPath,
        '$artifact.maven-metadata.xml',
      ),
1132
      fileSystem.path.join(
1133 1134 1135 1136 1137 1138
        localEngineRepo.path,
        'io',
        'flutter',
        artifact,
        'maven-metadata.xml',
      ),
1139
      fileSystem,
1140 1141
    );
  }
1142 1143
  return localEngineRepo;
}
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

String _getAbiByLocalEnginePath(String engineOutPath) {
  String result = 'armeabi_v7a';
  if (engineOutPath.contains('x86')) {
    result = 'x86';
  } else if (engineOutPath.contains('x64')) {
    result = 'x86_64';
  } else if (engineOutPath.contains('arm64')) {
    result = 'arm64_v8a';
  }
  return result;
}

String _getTargetPlatformByLocalEnginePath(String engineOutPath) {
  String result = 'android-arm';
  if (engineOutPath.contains('x86')) {
    result = 'android-x86';
  } else if (engineOutPath.contains('x64')) {
    result = 'android-x64';
  } else if (engineOutPath.contains('arm64')) {
    result = 'android-arm64';
  }
  return result;
}