gradle.dart 18.4 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import '../android/android_sdk.dart';
8
import '../artifacts.dart';
9
import '../base/common.dart';
10
import '../base/file_system.dart';
11 12
import '../base/logger.dart';
import '../base/os.dart';
13
import '../base/platform.dart';
14 15 16
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
17
import '../bundle.dart' as bundle;
18
import '../cache.dart';
19
import '../flutter_manifest.dart';
20 21
import '../globals.dart';
import 'android_sdk.dart';
22
import 'android_studio.dart';
23 24

const String gradleManifestPath = 'android/app/src/main/AndroidManifest.xml';
25
const String gradleAppOutV1 = 'android/app/build/outputs/apk/app-debug.apk';
26
const String gradleAppOutDirV1 = 'android/app/build/outputs/apk';
27
const String gradleVersion = '4.1';
28
final RegExp _assembleTaskPattern = new RegExp(r'assemble([^:]+): task ');
29

30
GradleProject _cachedGradleProject;
31
String _cachedGradleExecutable;
32

33 34 35 36
enum FlutterPluginVersion {
  none,
  v1,
  v2,
37
  managed,
38
}
39

40 41 42 43 44 45 46 47
// Investigation documented in #13975 suggests the filter should be a subset
// of the impact of -q, but users insist they see the error message sometimes
// anyway.  If we can prove it really is impossible, delete the filter.
final RegExp ndkMessageFilter = new RegExp(r'^(?!NDK is missing a ".*" directory'
  r'|If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning'
  r'|If you are using NDK, verify the ndk.dir is set to a valid NDK directory.  It is currently set to .*)');


48
bool isProjectUsingGradle() {
49
  return fs.isFileSync('android/build.gradle');
50 51
}

52
FlutterPluginVersion get flutterPluginVersion {
53
  final File plugin = fs.file('android/buildSrc/src/main/groovy/FlutterPlugin.groovy');
54
  if (plugin.existsSync()) {
55
    final String packageLine = plugin.readAsLinesSync().skip(4).first;
56
    if (packageLine == 'package io.flutter.gradle') {
57 58 59
      return FlutterPluginVersion.v2;
    }
    return FlutterPluginVersion.v1;
60
  }
61
  final File appGradle = fs.file('android/app/build.gradle');
62 63
  if (appGradle.existsSync()) {
    for (String line in appGradle.readAsLinesSync()) {
64
      if (line.contains(new RegExp(r'apply from: .*/flutter.gradle'))) {
65 66 67
        return FlutterPluginVersion.managed;
      }
    }
68
  }
69
  return FlutterPluginVersion.none;
70 71
}

72 73
/// Returns the path to the apk file created by [buildGradleProject], relative
/// to current directory.
74
Future<String> getGradleAppOut() async {
75 76 77 78 79
  switch (flutterPluginVersion) {
    case FlutterPluginVersion.none:
      // Fall through. Pretend we're v1, and just go with it.
    case FlutterPluginVersion.v1:
      return gradleAppOutV1;
80 81
    case FlutterPluginVersion.managed:
      // Fall through. The managed plugin matches plugin v2 for now.
82
    case FlutterPluginVersion.v2:
83
      return fs.path.relative(fs.path.join((await _gradleProject()).apkDirectory, 'app.apk'));
84 85 86 87
  }
  return null;
}

88 89 90
Future<GradleProject> _gradleProject() async {
  _cachedGradleProject ??= await _readGradleProject();
  return _cachedGradleProject;
91 92
}

93 94
// Note: Dependencies are resolved and possibly downloaded as a side-effect
// of calculating the app properties using Gradle. This may take minutes.
95
Future<GradleProject> _readGradleProject() async {
96
  final String gradle = await _ensureGradle();
97
  await updateLocalProperties();
98
  try {
99 100
    final Status status = logger.startProgress('Resolving dependencies...', expectSlowOperation: true);
    final RunResult runResult = await runCheckedAsync(
101 102
      <String>[gradle, 'app:properties'],
      workingDirectory: 'android',
103
      environment: _gradleEnv,
104
    );
105
    final String properties = runResult.stdout.trim();
106
    final GradleProject project = new GradleProject.fromAppProperties(properties);
107
    status.stop();
108
    return project;
109
  } catch (e) {
110
    if (flutterPluginVersion == FlutterPluginVersion.managed) {
111 112
      // Handle known exceptions. This will exit if handled.
      handleKnownGradleExceptions(e);
113

114 115 116
      // Print a general Gradle error and exit.
      printError('* Error running Gradle:\n$e\n');
      throwToolExit('Please review your Gradle project setup in the android/ folder.');
117
    }
118 119
  }
  // Fall back to the default
120
  return new GradleProject(<String>['debug', 'profile', 'release'], <String>[], gradleAppOutDirV1);
121 122
}

123 124 125 126
void handleKnownGradleExceptions(String exceptionString) {
  // Handle Gradle error thrown when Gradle needs to download additional
  // Android SDK components (e.g. Platform Tools), and the license
  // for that component has not been accepted.
127
  const String matcher =
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    r'You have not accepted the license agreements of the following SDK components:'
    r'\s*\[(.+)\]';
  final RegExp licenseFailure = new RegExp(matcher, multiLine: true);
  final Match licenseMatch = licenseFailure.firstMatch(exceptionString);
  if (licenseMatch != null) {
    final String missingLicenses = licenseMatch.group(1);
    final String errorMessage =
      '\n\n* Error running Gradle:\n'
      'Unable to download needed Android SDK components, as the following licenses have not been accepted:\n'
      '$missingLicenses\n\n'
      'To resolve this, please run the following command in a Terminal:\n'
      'flutter doctor --android-licenses';
    throwToolExit(errorMessage);
  }
}

144 145
String _locateGradlewExecutable(Directory directory) {
  final File gradle = directory.childFile(
146
    platform.isWindows ? 'gradlew.bat' : 'gradlew',
147
  );
148

149 150
  if (gradle.existsSync()) {
    os.makeExecutable(gradle);
151
    return gradle.absolute.path;
152 153 154 155 156
  } else {
    return null;
  }
}

157 158 159 160 161 162 163 164
Future<String> _ensureGradle() async {
  _cachedGradleExecutable ??= await _initializeGradle();
  return _cachedGradleExecutable;
}

// Note: Gradle may be bootstrapped and possibly downloaded as a side-effect
// of validating the Gradle executable. This may take several seconds.
Future<String> _initializeGradle() async {
165
  final Directory android = fs.directory('android');
166
  final Status status = logger.startProgress('Initializing gradle...', expectSlowOperation: true);
167
  String gradle = _locateGradlewExecutable(android);
168
  if (gradle == null) {
169 170
    injectGradleWrapper(android);
    gradle = _locateGradlewExecutable(android);
171
  }
172 173 174 175 176 177 178
  if (gradle == null)
    throwToolExit('Unable to locate gradlew script');
  printTrace('Using gradle from $gradle.');
  // Validates the Gradle executable by asking for its version.
  // Makes Gradle Wrapper download and install Gradle distribution, if needed.
  await runCheckedAsync(<String>[gradle, '-v'], environment: _gradleEnv);
  status.stop();
179
  return gradle;
180 181
}

182 183 184 185 186 187 188
/// Injects the Gradle wrapper into the specified directory.
void injectGradleWrapper(Directory directory) {
  copyDirectorySync(cache.getArtifactDirectory('gradle_wrapper'), directory);
  _locateGradlewExecutable(directory);
  final File propertiesFile = directory.childFile(fs.path.join('gradle', 'wrapper', 'gradle-wrapper.properties'));
  if (!propertiesFile.existsSync()) {
    propertiesFile.writeAsStringSync('''
189 190 191 192 193 194 195 196 197 198
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-$gradleVersion-all.zip
''', flush: true,
    );
  }
}

199 200 201
/// Overwrite android/local.properties in the specified Flutter project, if needed.
///
/// Throws, if `pubspec.yaml` or Android SDK cannot be located.
202
Future<void> updateLocalProperties({String projectPath, BuildInfo buildInfo}) async {
203 204 205
  final Directory android = (projectPath == null)
      ? fs.directory('android')
      : fs.directory(fs.path.join(projectPath, 'android'));
206 207 208
  final String flutterManifest = (projectPath == null)
      ? fs.path.join(bundle.defaultManifestPath)
      : fs.path.join(projectPath, bundle.defaultManifestPath);
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  if (androidSdk == null) {
    throwToolExit('Unable to locate Android SDK. Please run `flutter doctor` for more details.');
  }
  FlutterManifest manifest;
  try {
    manifest = await FlutterManifest.createFromPath(flutterManifest);
  } catch (error) {
    throwToolExit('Failed to load pubspec.yaml: $error');
  }
  updateLocalPropertiesSync(android, manifest, buildInfo);
}

/// Overwrite local.properties in the specified directory, if needed.
void updateLocalPropertiesSync(Directory android, FlutterManifest manifest, [BuildInfo buildInfo]) {
  final File localProperties = android.childFile('local.properties');
224 225 226 227 228 229 230 231 232 233
  bool changed = false;

  SettingsFile settings;
  if (localProperties.existsSync()) {
    settings = new SettingsFile.parseFromFile(localProperties);
  } else {
    settings = new SettingsFile();
    changed = true;
  }

234 235 236 237 238
  void changeIfNecessary(String key, String value) {
    if (settings.values[key] != value) {
      settings.values[key] = value;
      changed = true;
    }
239 240
  }

241 242 243 244 245
  if (androidSdk != null)
    changeIfNecessary('sdk.dir', escapePath(androidSdk.directory));
  changeIfNecessary('flutter.sdk', escapePath(Cache.flutterRoot));
  if (buildInfo != null)
    changeIfNecessary('flutter.buildMode', buildInfo.modeName);
246
  final String buildName = buildInfo?.buildName ?? manifest.buildName;
247 248
  if (buildName != null)
    changeIfNecessary('flutter.versionName', buildName);
249
  final int buildNumber = buildInfo?.buildNumber ?? manifest.buildNumber;
250 251
  if (buildNumber != null)
    changeIfNecessary('flutter.versionCode', '$buildNumber');
252

253 254
  if (changed)
    settings.writeContents(localProperties);
255 256
}

257
Future<Null> buildGradleProject(BuildInfo buildInfo, String target) async {
258
  // Update the local.properties file with the build mode, version name and code.
259 260 261
  // FlutterPlugin v1 reads local.properties to determine build mode. Plugin v2
  // uses the standard Android way to determine what to build, but we still
  // update local.properties, in case we want to use it in the future.
262 263 264 265 266
  // Version name and number are provided by the pubspec.yaml file
  // and can be overwritten with flutter build command.
  // The default Gradle script reads the version name and number
  // from the local.properties file.
  await updateLocalProperties(buildInfo: buildInfo);
267

268
  final String gradle = await _ensureGradle();
269 270 271 272 273

  switch (flutterPluginVersion) {
    case FlutterPluginVersion.none:
      // Fall through. Pretend it's v1, and just go for it.
    case FlutterPluginVersion.v1:
274
      return _buildGradleProjectV1(gradle);
275 276
    case FlutterPluginVersion.managed:
      // Fall through. Managed plugin builds the same way as plugin v2.
277
    case FlutterPluginVersion.v2:
278
      return _buildGradleProjectV2(gradle, buildInfo, target);
279 280 281
  }
}

282 283 284 285
Future<Null> _buildGradleProjectV1(String gradle) async {
  // Run 'gradlew build'.
  final Status status = logger.startProgress('Running \'gradlew build\'...', expectSlowOperation: true);
  final int exitCode = await runCommandAndStreamOutput(
286
    <String>[fs.file(gradle).absolute.path, 'build'],
287
    workingDirectory: 'android',
288 289
    allowReentrantFlutter: true,
    environment: _gradleEnv,
290
  );
Devon Carew's avatar
Devon Carew committed
291
  status.stop();
292

293 294
  if (exitCode != 0)
    throwToolExit('Gradle build failed: $exitCode', exitCode: exitCode);
295

296
  printStatus('Built $gradleAppOutV1.');
297 298
}

299
Future<Null> _buildGradleProjectV2(String gradle, BuildInfo buildInfo, String target) async {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
  final GradleProject project = await _gradleProject();
  final String assembleTask = project.assembleTaskFor(buildInfo);
  if (assembleTask == null) {
    printError('');
    printError('The Gradle project does not define a task suitable for the requested build.');
    if (!project.buildTypes.contains(buildInfo.modeName)) {
      printError('Review the android/app/build.gradle file and ensure it defines a ${buildInfo.modeName} build type.');
    } else {
      if (project.productFlavors.isEmpty) {
        printError('The android/app/build.gradle file does not define any custom product flavors.');
        printError('You cannot use the --flavor option.');
      } else {
        printError('The android/app/build.gradle file defines product flavors: ${project.productFlavors.join(', ')}');
        printError('You must specify a --flavor option to select one of them.');
      }
      throwToolExit('Gradle build aborted.');
    }
  }
318
  final Status status = logger.startProgress('Running \'gradlew $assembleTask\'...', expectSlowOperation: true);
319 320
  final String gradlePath = fs.file(gradle).absolute.path;
  final List<String> command = <String>[gradlePath];
321 322 323
  if (logger.isVerbose) {
    command.add('-Pverbose=true');
  } else {
324 325 326
    command.add('-q');
  }
  if (artifacts is LocalEngineArtifacts) {
327
    final LocalEngineArtifacts localEngineArtifacts = artifacts;
328 329 330
    printTrace('Using local engine: ${localEngineArtifacts.engineOutPath}');
    command.add('-PlocalEngineOut=${localEngineArtifacts.engineOutPath}');
  }
331 332 333
  if (target != null) {
    command.add('-Ptarget=$target');
  }
334 335 336 337
  if (buildInfo.previewDart2) {
    command.add('-Ppreview-dart-2=true');
    if (buildInfo.trackWidgetCreation)
      command.add('-Ptrack-widget-creation=true');
338 339
    if (buildInfo.buildSnapshot)
      command.add('-Pbuild-snapshot=true');
340 341 342 343 344 345 346 347 348 349 350
    if (buildInfo.extraFrontEndOptions != null)
      command.add('-Pextra-front-end-options=${buildInfo.extraFrontEndOptions}');
    if (buildInfo.extraGenSnapshotOptions != null)
      command.add('-Pextra-gen-snapshot-options=${buildInfo.extraGenSnapshotOptions}');
    if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty)
      command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}');
    if (buildInfo.fileSystemScheme != null)
      command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}');
  } else {
    command.add('-Ppreview-dart-2=false');
  }
351 352
  if (buildInfo.buildSharedLibrary && androidSdk.ndk != null) {
    command.add('-Pbuild-shared-library=true');
353
  }
354 355
  if (buildInfo.targetPlatform != null)
    command.add('-Ptarget-platform=${getNameForTargetPlatform(buildInfo.targetPlatform)}');
356

357
  command.add(assembleTask);
358
  final int exitCode = await runCommandAndStreamOutput(
359 360
      command,
      workingDirectory: 'android',
361 362
      allowReentrantFlutter: true,
      environment: _gradleEnv,
363
      filter: logger.isVerbose ? null : ndkMessageFilter,
364 365 366
  );
  status.stop();

367 368
  if (exitCode != 0)
    throwToolExit('Gradle build failed: $exitCode', exitCode: exitCode);
369

370
  final File apkFile = _findApkFile(project, buildInfo);
371 372
  if (apkFile == null)
    throwToolExit('Gradle build failed to produce an Android package.');
373
  // Copy the APK to app.apk, so `flutter run`, `flutter install`, etc. can find it.
374
  apkFile.copySync(fs.path.join(project.apkDirectory, 'app.apk'));
375

376 377
  printTrace('calculateSha: ${project.apkDirectory}/app.apk');
  final File apkShaFile = fs.file(fs.path.join(project.apkDirectory, 'app.apk.sha1'));
378 379
  apkShaFile.writeAsStringSync(calculateSha(apkFile));

380 381 382 383 384 385 386
  String appSize;
  if (buildInfo.mode == BuildMode.debug) {
    appSize = '';
  } else {
    appSize = ' (${getSizeAsMB(apkFile.lengthSync())})';
  }
  printStatus('Built ${fs.path.relative(apkFile.path)}$appSize.');
387 388 389 390 391 392 393 394 395 396 397 398
}

File _findApkFile(GradleProject project, BuildInfo buildInfo) {
  final String apkFileName = project.apkFileFor(buildInfo);
  if (apkFileName == null)
    return null;
  File apkFile = fs.file(fs.path.join(project.apkDirectory, apkFileName));
  if (apkFile.existsSync())
    return apkFile;
  apkFile = fs.file(fs.path.join(project.apkDirectory, buildInfo.modeName, apkFileName));
  if (apkFile.existsSync())
    return apkFile;
399 400 401 402 403 404
  if (buildInfo.flavor != null) {
    // Android Studio Gradle plugin v3 adds flavor to path.
    apkFile = fs.file(fs.path.join(project.apkDirectory, buildInfo.flavor, buildInfo.modeName, apkFileName));
    if (apkFile.existsSync())
      return apkFile;
  }
405
  return null;
406
}
407 408 409 410 411 412 413 414 415

Map<String, String> get _gradleEnv {
  final Map<String, String> env = new Map<String, String>.from(platform.environment);
  if (javaPath != null) {
    // Use java bundled with Android Studio.
    env['JAVA_HOME'] = javaPath;
  }
  return env;
}
416 417 418 419 420 421 422 423 424 425 426 427 428 429

class GradleProject {
  GradleProject(this.buildTypes, this.productFlavors, this.apkDirectory);

  factory GradleProject.fromAppProperties(String properties) {
    // Extract build directory.
    final String buildDir = properties
        .split('\n')
        .firstWhere((String s) => s.startsWith('buildDir: '))
        .substring('buildDir: '.length)
        .trim();

    // Extract build types and product flavors.
    final Set<String> variants = new Set<String>();
430
    for (String s in properties.split('\n')) {
431 432 433 434 435 436
      final Match match = _assembleTaskPattern.matchAsPrefix(s);
      if (match != null) {
        final String variant = match.group(1).toLowerCase();
        if (!variant.endsWith('test'))
          variants.add(variant);
      }
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
    final Set<String> buildTypes = new Set<String>();
    final Set<String> productFlavors = new Set<String>();
    for (final String variant1 in variants) {
      for (final String variant2 in variants) {
        if (variant2.startsWith(variant1) && variant2 != variant1) {
          final String buildType = variant2.substring(variant1.length);
          if (variants.contains(buildType)) {
            buildTypes.add(buildType);
            productFlavors.add(variant1);
          }
        }
      }
    }
    if (productFlavors.isEmpty)
      buildTypes.addAll(variants);
    return new GradleProject(
      buildTypes.toList(),
      productFlavors.toList(),
      fs.path.normalize(fs.path.join(buildDir, 'outputs', 'apk')),
    );
  }

  final List<String> buildTypes;
  final List<String> productFlavors;
  final String apkDirectory;

  String _buildTypeFor(BuildInfo buildInfo) {
    if (buildTypes.contains(buildInfo.modeName))
      return buildInfo.modeName;
    return null;
  }

  String _productFlavorFor(BuildInfo buildInfo) {
    if (buildInfo.flavor == null)
      return productFlavors.isEmpty ? '' : null;
    else if (productFlavors.contains(buildInfo.flavor.toLowerCase()))
      return buildInfo.flavor.toLowerCase();
    else
      return null;
  }

  String assembleTaskFor(BuildInfo buildInfo) {
    final String buildType = _buildTypeFor(buildInfo);
    final String productFlavor = _productFlavorFor(buildInfo);
    if (buildType == null || productFlavor == null)
      return null;
    return 'assemble${toTitleCase(productFlavor)}${toTitleCase(buildType)}';
  }

  String apkFileFor(BuildInfo buildInfo) {
    final String buildType = _buildTypeFor(buildInfo);
    final String productFlavor = _productFlavorFor(buildInfo);
    if (buildType == null || productFlavor == null)
      return null;
    final String flavorString = productFlavor.isEmpty ? '' : '-' + productFlavor;
    return 'app$flavorString-$buildType.apk';
  }
}