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

import 'package:meta/meta.dart';
6
import 'package:process/process.dart';
7
import 'package:unified_analytics/unified_analytics.dart';
8 9 10

import '../base/common.dart';
import '../base/file_system.dart';
11 12 13
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
14 15
import '../base/utils.dart';
import '../base/version.dart';
16
import '../base/version_range.dart';
17 18
import '../build_info.dart';
import '../cache.dart';
19
import '../globals.dart' as globals;
20 21
import '../project.dart';
import '../reporting/reporting.dart';
22
import 'android_sdk.dart';
23

24 25 26 27 28
// These are the versions used in the project templates.
//
// In general, Flutter aims to default to the latest version.
// However, this currently requires to migrate existing integration tests to the latest supported values.
//
29
// Please see the README before changing any of these values.
30
const String templateDefaultGradleVersion = '7.6.3';
31
const String templateAndroidGradlePluginVersion = '7.3.0';
32
const String templateAndroidGradlePluginVersionForModule = '7.3.0';
33
const String templateKotlinGradlePluginVersion = '1.7.10';
34

35 36 37 38 39 40 41
// The Flutter Gradle Plugin is only applied to app projects, and modules that
// are built from source using (`include_flutter.groovy`). The remaining
// projects are: plugins, and modules compiled as AARs. In modules, the
// ephemeral directory `.android` is always regenerated after `flutter pub get`,
// so new versions are picked up after a Flutter upgrade.
//
// Please see the README before changing any of these values.
42
const String compileSdkVersion = '34';
43
const String minSdkVersion = '21';
44
const String targetSdkVersion = '33';
45
const String ndkVersion = '23.1.7779620';
46

47 48 49 50 51 52

// Update these when new major versions of Java are supported by new Gradle
// versions that we support.
// Source of truth: https://docs.gradle.org/current/userguide/compatibility.html
const String oneMajorVersionHigherJavaVersion = '20';

53
// Update this when new versions of Gradle come out including minor versions
54
// and should correspond to the maximum Gradle version we test in CI.
55 56 57
//
// Supported here means supported by the tooling for
// flutter analyze --suggestions and does not imply broader flutter support.
58 59
const String maxKnownAndSupportedGradleVersion = '8.0.2';

60
// Update this when new versions of AGP come out.
61 62 63
//
// Supported here means tooling is aware of this version's Java <-> AGP
// compatibility.
64
@visibleForTesting
65 66 67 68 69 70 71 72
const String maxKnownAndSupportedAgpVersion = '8.1';

// Update this when new versions of AGP come out.
const String maxKnownAgpVersion = '8.3';

// Oldest documented version of AGP that has a listed minimum
// compatible Java version.
const String oldestDocumentedJavaAgpCompatibilityVersion = '4.2';
73

74 75 76 77 78
// Constant used in [_buildAndroidGradlePluginRegExp] and
// [_settingsAndroidGradlePluginRegExp] to identify the version section.
const String _versionGroupName = 'version';

// AGP can be defined in build.gradle
79 80
// Expected content:
// "classpath 'com.android.tools.build:gradle:7.3.0'"
81 82 83 84 85 86 87 88 89 90 91
// ?<version> is used to name the version group which helps with extraction.
final RegExp _buildAndroidGradlePluginRegExp =
    RegExp(r'com\.android\.tools\.build:gradle:(?<version>\d+\.\d+\.\d+)');

// AGP can be defined in settings.gradle.
// Expected content:
// "id "com.android.application" version "{{agpVersion}}""
// ?<version> is used to name the version group which helps with extraction.
final RegExp _settingsAndroidGradlePluginRegExp = RegExp(
    r'^\s+id\s+"com.android.application"\s+version\s+"(?<version>\d+\.\d+\.\d+)"',
    multiLine: true);
92

93 94 95 96 97
// Expected content format (with lines above and below).
// Version can have 2 or 3 numbers.
// 'distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip'
// '^\s*' protects against commented out lines.
final RegExp distributionUrlRegex =
98
    RegExp(r'^\s*distributionUrl\s*=\s*.*\.zip', multiLine: true);
99 100 101 102 103

// Modified version of the gradle distribution url match designed to only match
// gradle.org urls so that we can guarantee any modifications to the url
// still points to a hosted zip.
final RegExp gradleOrgVersionMatch =
104
  RegExp(
105 106
    r'^\s*distributionUrl\s*=\s*https\\://services\.gradle\.org/distributions/gradle-((?:\d|\.)+)-(.*)\.zip',
    multiLine: true
107 108 109
  );

// This matches uncommented minSdkVersion lines in the module-level build.gradle
110 111 112 113 114
// file which have minSdkVersion 16,17, 18, 19, or 20.
final RegExp tooOldMinSdkVersionMatch = RegExp(
  r'(?<=^\s*)minSdkVersion (1[6789]|20)(?=\s*(?://|$))',
  multiLine: true,
);
115

116 117 118 119 120 121 122 123 124 125 126
// From https://docs.gradle.org/current/userguide/command_line_interface.html#command_line_interface
const String gradleVersionFlag = r'--version';

// Directory under android/ that gradle uses to store gradle information.
// Regularly used with [gradleWrapperDirectory] and
// [gradleWrapperPropertiesFilename].
// Different from the directory of gradle files stored in
// `_cache.getArtifactDirectory('gradle_wrapper')`
const String gradleDirectoryName = 'gradle';
const String gradleWrapperDirectoryName = 'wrapper';
const String gradleWrapperPropertiesFilename = 'gradle-wrapper.properties';
127

128 129
/// Provides utilities to run a Gradle task, such as finding the Gradle executable
/// or constructing a Gradle project.
130
class GradleUtils {
131
  GradleUtils({
132 133 134 135
    required Platform platform,
    required Logger logger,
    required Cache cache,
    required OperatingSystemUtils operatingSystemUtils,
136
  })  : _platform = platform,
137 138 139 140 141 142 143 144 145
       _logger = logger,
       _cache = cache,
       _operatingSystemUtils = operatingSystemUtils;

  final Cache _cache;
  final Platform _platform;
  final Logger _logger;
  final OperatingSystemUtils _operatingSystemUtils;

146 147 148 149
  /// Gets the Gradle executable path and prepares the Gradle project.
  /// This is the `gradlew` or `gradlew.bat` script in the `android/` directory.
  String getExecutable(FlutterProject project) {
    final Directory androidDir = project.android.hostAppGradleRoot;
150
    injectGradleWrapperIfNeeded(androidDir);
151

152 153
    final File gradle = androidDir.childFile(getGradlewFileName(_platform));

154
    if (gradle.existsSync()) {
155
      _logger.printTrace('Using gradle from ${gradle.absolute.path}.');
156 157
      // If the Gradle executable doesn't have execute permission,
      // then attempt to set it.
158
      _operatingSystemUtils.makeExecutable(gradle);
159 160 161
      return gradle.absolute.path;
    }
    throwToolExit(
162 163
       'Unable to locate gradlew script. Please check that ${gradle.path} '
       'exists or that ${gradle.dirname} can be read.');
164 165
  }

166 167
  /// Injects the Gradle wrapper files if any of these files don't exist in [directory].
  void injectGradleWrapperIfNeeded(Directory directory) {
168 169
    copyDirectory(
      _cache.getArtifactDirectory('gradle_wrapper'),
170 171 172 173 174
      directory,
      shouldCopyFile: (File sourceFile, File destinationFile) {
        // Don't override the existing files in the project.
        return !destinationFile.existsSync();
      },
175 176 177
      onFileCopied: (File source, File dest) {
        _operatingSystemUtils.makeExecutable(dest);
      }
178 179
    );
    // Add the `gradle-wrapper.properties` file if it doesn't exist.
180
    final Directory propertiesDirectory = directory
181 182 183 184
        .childDirectory(gradleDirectoryName)
        .childDirectory(gradleWrapperDirectoryName);
    final File propertiesFile =
        propertiesDirectory.childFile(gradleWrapperPropertiesFilename);
185 186 187 188 189

    if (propertiesFile.existsSync()) {
      return;
    }
    propertiesDirectory.createSync(recursive: true);
190 191
    final String gradleVersion =
        getGradleVersionForAndroidPlugin(directory, _logger);
192
    final String propertyContents = '''
193 194 195 196 197
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\\://services.gradle.org/distributions/gradle-$gradleVersion-all.zip
198 199
''';
    propertiesFile.writeAsStringSync(propertyContents);
200 201 202 203 204 205 206 207
  }
}

/// Returns the Gradle version that the current Android plugin depends on when found,
/// otherwise it returns a default version.
///
/// The Android plugin version is specified in the [build.gradle] file within
/// the project's Android directory.
208
String getGradleVersionForAndroidPlugin(Directory directory, Logger logger) {
209 210 211 212 213 214 215
  const String buildFileName = 'build.gradle/build.gradle.kts';

  File buildFile = directory.childFile('build.gradle');
  if (!buildFile.existsSync()) {
    buildFile = directory.childFile('build.gradle.kts');
  }

216
  if (!buildFile.existsSync()) {
217
    logger.printTrace(
218
        "$buildFileName doesn't exist, assuming Gradle version: $templateDefaultGradleVersion");
219
    return templateDefaultGradleVersion;
220 221
  }
  final String buildFileContent = buildFile.readAsStringSync();
222
  final Iterable<Match> pluginMatches = _buildAndroidGradlePluginRegExp.allMatches(buildFileContent);
223
  if (pluginMatches.isEmpty) {
224
    logger.printTrace("$buildFileName doesn't provide an AGP version, assuming Gradle version: $templateDefaultGradleVersion");
225
    return templateDefaultGradleVersion;
226
  }
227
  final String? androidPluginVersion = pluginMatches.first.group(1);
228
  logger.printTrace('$buildFileName provides AGP version: $androidPluginVersion');
229
  return getGradleVersionFor(androidPluginVersion ?? 'unknown');
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
/// Returns the gradle file from the top level directory.
/// The returned file is not guaranteed to be present.
File getGradleWrapperFile(Directory directory) {
  return directory.childDirectory(gradleDirectoryName)
      .childDirectory(gradleWrapperDirectoryName)
      .childFile(gradleWrapperPropertiesFilename);
}

/// Parses the gradle wrapper distribution url to return a string containing
/// the version number.
///
/// Expected input is of the form '...gradle-7.4.2-all.zip', and the output
/// would be of the form '7.4.2'.
String? parseGradleVersionFromDistributionUrl(String? distributionUrl) {
  if (distributionUrl == null) {
    return null;
  }
  final List<String> zipParts = distributionUrl.split('-');
  if (zipParts.length < 2) {
    return null;
  }
  return zipParts[1];
}

256 257 258 259
/// Returns either the gradle-wrapper.properties value from the passed in
/// [directory] or if not present the version available in local path.
///
/// If gradle version is not found null is returned.
260
/// [directory] should be an android directory with a build.gradle file.
261 262
Future<String?> getGradleVersion(
    Directory directory, Logger logger, ProcessManager processManager) async {
263
  final File propertiesFile = getGradleWrapperFile(directory);
264 265 266 267 268 269 270

  if (propertiesFile.existsSync()) {
    final String wrapperFileContent = propertiesFile.readAsStringSync();

    final RegExpMatch? distributionUrl =
        distributionUrlRegex.firstMatch(wrapperFileContent);
    if (distributionUrl != null) {
271 272 273 274
      final String? gradleVersion =
          parseGradleVersionFromDistributionUrl(distributionUrl.group(0));
      if (gradleVersion != null) {
        return gradleVersion;
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
      } else {
        // Did not find gradle zip url. Likely this is a bug in our parsing.
        logger.printWarning(_formatParseWarning(wrapperFileContent));
      }
    } else {
      // If no distributionUrl log then treat as if there was no propertiesFile.
      logger.printTrace(
          '$propertiesFile does not provide a Gradle version falling back to system gradle.');
    }
  } else {
    // Could not find properties file.
    logger.printTrace(
        '$propertiesFile does not exist falling back to system gradle');
  }
  // System installed Gradle version.
  if (processManager.canRun('gradle')) {
    final String gradleVersionVerbose =
        (await processManager.run(<String>['gradle', gradleVersionFlag])).stdout
            as String;
    // Expected format:
/*

------------------------------------------------------------
Gradle 7.6
------------------------------------------------------------

Build time:   2022-11-25 13:35:10 UTC
Revision:     daece9dbc5b79370cc8e4fd6fe4b2cd400e150a8

Kotlin:       1.7.10
Groovy:       3.0.13
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          17.0.6 (Homebrew 17.0.6+0)
OS:           Mac OS X 13.2.1 aarch64
    */
    // Observation shows that the version can have 2 or 3 numbers.
    // Inner parentheticals `(\.\d+)?` denote the optional third value.
    // Outer parentheticals `Gradle (...)` denote a grouping used to extract
    // the version number.
    final RegExp gradleVersionRegex = RegExp(r'Gradle\s+(\d+\.\d+(?:\.\d+)?)');
    final RegExpMatch? version =
        gradleVersionRegex.firstMatch(gradleVersionVerbose);
    if (version == null) {
318
      // Most likely a bug in our parse implementation/regex.
319 320 321 322 323 324 325 326
      logger.printWarning(_formatParseWarning(gradleVersionVerbose));
      return null;
    }
    return version.group(1);
  } else {
    logger.printTrace('Could not run system gradle');
    return null;
  }
327 328
}

329 330 331
/// Returns the Android Gradle Plugin (AGP) version that the current project
/// depends on when found, null otherwise.
///
332 333 334
/// The Android plugin version is specified in the [build.gradle] or
/// [settings.gradle] file within the project's
/// Android directory ([androidDirectory]).
335
String? getAgpVersion(Directory androidDirectory, Logger logger) {
336 337 338 339 340
  File buildFile = androidDirectory.childFile('build.gradle');
  if (!buildFile.existsSync()) {
    buildFile = androidDirectory.childFile('build.gradle.kts');
  }

341
  if (!buildFile.existsSync()) {
342
    logger.printTrace('Can not find build.gradle/build.gradle.kts in $androidDirectory');
343 344 345
    return null;
  }
  final String buildFileContent = buildFile.readAsStringSync();
346 347 348 349 350 351 352 353 354 355 356 357 358
  final RegExpMatch? buildMatch =
      _buildAndroidGradlePluginRegExp.firstMatch(buildFileContent);
  if (buildMatch != null) {
    final String? androidPluginVersion =
        buildMatch.namedGroup(_versionGroupName);
    logger.printTrace('$buildFile provides AGP version: $androidPluginVersion');
    return androidPluginVersion;
  }
  logger.printTrace(
      "$buildFile doesn't provide an AGP version. Checking settings.");
  final File settingsFile = androidDirectory.childFile('settings.gradle');
  if (!settingsFile.existsSync()) {
    logger.printTrace('$settingsFile does not exist.');
359 360
    return null;
  }
361 362 363 364 365 366 367 368 369 370 371 372 373
  final String settingsFileContent = settingsFile.readAsStringSync();
  final RegExpMatch? settingsMatch =
      _settingsAndroidGradlePluginRegExp.firstMatch(settingsFileContent);

  if (settingsMatch != null) {
    final String? androidPluginVersion =
        settingsMatch.namedGroup(_versionGroupName);
    logger.printTrace(
        '$settingsFile provides AGP version: $androidPluginVersion');
    return androidPluginVersion;
  }
  logger.printTrace("$settingsFile doesn't provide an AGP version.");
  return null;
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
}

String _formatParseWarning(String content) {
  return 'Could not parse gradle version from: \n'
      '$content \n'
      'If there is a version please look for an existing bug '
      'https://github.com/flutter/flutter/issues/'
      ' and if one does not exist file a new issue.';
}

// Validate that Gradle version and AGP are compatible with each other.
//
// Returns true if versions are compatible.
// Null Gradle version or AGP version returns false.
// If compatibility can not be evaluated returns false.
// If versions are newer than the max known version a warning is logged and true
// returned.
//
// Source of truth found here:
// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
394
// AGP has a minimum version of gradle required but no max starting at
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
// AGP version 2.3.0+.
bool validateGradleAndAgp(Logger logger,
    {required String? gradleV, required String? agpV}) {

  const String oldestSupportedAgpVersion = '3.3.0';
  const String oldestSupportedGradleVersion = '4.10.1';

  if (gradleV == null || agpV == null) {
    logger
        .printTrace('Gradle version or AGP version unknown ($gradleV, $agpV).');
    return false;
  }

  // First check if versions are too old.
  if (isWithinVersionRange(agpV,
      min: '0.0', max: oldestSupportedAgpVersion, inclusiveMax: false)) {
    logger.printTrace('AGP Version: $agpV is too old.');
    return false;
  }
  if (isWithinVersionRange(gradleV,
      min: '0.0', max: oldestSupportedGradleVersion, inclusiveMax: false)) {
    logger.printTrace('Gradle Version: $gradleV is too old.');
    return false;
  }

  // Check highest supported version before checking unknown versions.
421
  if (isWithinVersionRange(agpV, min: '8.0', max: maxKnownAndSupportedAgpVersion)) {
422
    return isWithinVersionRange(gradleV,
423
        min: '8.0', max: maxKnownAndSupportedGradleVersion);
424 425 426
  }
  // Check if versions are newer than the max known versions.
  if (isWithinVersionRange(agpV,
427
      min: maxKnownAndSupportedAgpVersion, max: '100.100')) {
428 429 430 431 432 433 434 435 436 437 438 439
    // Assume versions we do not know about are valid but log.
    final bool validGradle =
        isWithinVersionRange(gradleV, min: '8.0', max: '100.00');
    logger.printTrace('Newer than known AGP version ($agpV), gradle ($gradleV).'
        '\n Treating as valid configuration.');
    return validGradle;
  }

  // Begin Known Gradle <-> AGP validation.
  // Max agp here is a made up version to contain all 7.4 changes.
  if (isWithinVersionRange(agpV, min: '7.4', max: '7.5')) {
    return isWithinVersionRange(gradleV,
440
        min: '7.5', max: maxKnownAndSupportedGradleVersion);
441
  }
442 443 444
  if (isWithinVersionRange(agpV,
      min: '7.3', max: '7.4', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
445
        min: '7.4', max: maxKnownAndSupportedGradleVersion);
446
  }
447 448 449
  if (isWithinVersionRange(agpV,
      min: '7.2', max: '7.3', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
450
        min: '7.3.3', max: maxKnownAndSupportedGradleVersion);
451
  }
452 453 454
  if (isWithinVersionRange(agpV,
      min: '7.1', max: '7.2', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
455
        min: '7.2', max: maxKnownAndSupportedGradleVersion);
456
  }
457 458 459
  if (isWithinVersionRange(agpV,
      min: '7.0', max: '7.1', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
460
        min: '7.0', max: maxKnownAndSupportedGradleVersion);
461
  }
462 463 464
  if (isWithinVersionRange(agpV,
      min: '4.2.0', max: '7.0', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
465
        min: '6.7.1', max: maxKnownAndSupportedGradleVersion);
466
  }
467 468 469
  if (isWithinVersionRange(agpV,
      min: '4.1.0', max: '4.2.0', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
470
        min: '6.5', max: maxKnownAndSupportedGradleVersion);
471 472 473 474
  }
  if (isWithinVersionRange(agpV,
      min: '4.0.0', max: '4.1.0', inclusiveMax: false)) {
    return isWithinVersionRange(gradleV,
475
        min: '6.1.1', max: maxKnownAndSupportedGradleVersion);
476 477 478 479 480 481 482
  }
  if (isWithinVersionRange(
    agpV,
    min: '3.6.0',
    max: '3.6.4',
  )) {
    return isWithinVersionRange(gradleV,
483
        min: '5.6.4', max: maxKnownAndSupportedGradleVersion);
484 485 486 487 488 489 490
  }
  if (isWithinVersionRange(
    agpV,
    min: '3.5.0',
    max: '3.5.4',
  )) {
    return isWithinVersionRange(gradleV,
491
        min: '5.4.1', max: maxKnownAndSupportedGradleVersion);
492 493 494 495 496 497 498
  }
  if (isWithinVersionRange(
    agpV,
    min: '3.4.0',
    max: '3.4.3',
  )) {
    return isWithinVersionRange(gradleV,
499
        min: '5.1.1', max: maxKnownAndSupportedGradleVersion);
500 501 502 503 504 505 506
  }
  if (isWithinVersionRange(
    agpV,
    min: '3.3.0',
    max: '3.3.3',
  )) {
    return isWithinVersionRange(gradleV,
507
        min: '4.10.1', max: maxKnownAndSupportedGradleVersion);
508 509 510 511 512 513
  }

  logger.printTrace('Unknown Gradle-Agp compatibility, $gradleV, $agpV');
  return false;
}

514 515 516 517 518 519
/// Validate that the [javaVersion] and Gradle version are compatible with
/// each other.
///
/// Source of truth:
/// https://docs.gradle.org/current/userguide/compatibility.html#java
bool validateJavaAndGradle(Logger logger,
520 521 522 523 524 525 526 527 528 529 530
    {required String? javaV, required String? gradleV}) {
  // https://docs.gradle.org/current/userguide/compatibility.html#java
  const String oldestSupportedJavaVersion = '1.8';
  const String oldestDocumentedJavaGradleCompatibility = '2.0';

  // Begin Java <-> Gradle validation.

  if (javaV == null || gradleV == null) {
    logger.printTrace(
        'Java version or Gradle version unknown ($javaV, $gradleV).');
    return false;
531
  }
532 533 534 535 536 537

  // First check if versions are too old.
  if (isWithinVersionRange(javaV,
      min: '1.1', max: oldestSupportedJavaVersion, inclusiveMax: false)) {
    logger.printTrace('Java Version: $javaV is too old.');
    return false;
538
  }
539 540 541 542
  if (isWithinVersionRange(gradleV,
      min: '0.0', max: oldestDocumentedJavaGradleCompatibility, inclusiveMax: false)) {
    logger.printTrace('Gradle Version: $gradleV is too old.');
    return false;
543
  }
544 545 546 547 548 549 550 551 552 553

  // Check if versions are newer than the max supported versions.
  if (isWithinVersionRange(
    javaV,
    min: oneMajorVersionHigherJavaVersion,
    max: '100.100',
  )) {
    // Assume versions Java versions newer than [maxSupportedJavaVersion]
    // required a higher gradle version.
    final bool validGradle = isWithinVersionRange(gradleV,
554
        min: maxKnownAndSupportedGradleVersion, max: '100.00');
555 556 557 558
    logger.printWarning(
        'Newer than known valid Java version ($javaV), gradle ($gradleV).'
        '\n Treating as valid configuration.');
    return validGradle;
559
  }
560 561

  // Begin known Java <-> Gradle evaluation.
562
  for (final JavaGradleCompat data in _javaGradleCompatList) {
563 564 565
    if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) {
      return isWithinVersionRange(gradleV, min: data.gradleMin, max: data.gradleMax);
    }
566
  }
567 568 569 570 571

  logger.printTrace('Unknown Java-Gradle compatibility $javaV, $gradleV');
  return false;
}

572 573 574
/// Returns compatibility information for the valid range of Gradle versions for
/// the specified Java version.
///
575
/// Returns null when the tooling has not documented the compatible Gradle
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
/// versions for the Java version (either the version is too old or too new). If
/// this seems like a mistake, the caller may need to update the
/// [_javaGradleCompatList] detailing Java/Gradle compatibility.
JavaGradleCompat? getValidGradleVersionRangeForJavaVersion(
  Logger logger, {
  required String javaV,
}) {
  for (final JavaGradleCompat data in _javaGradleCompatList) {
    if (isWithinVersionRange(javaV, min: data.javaMin, max: data.javaMax, inclusiveMax: false)) {
      return data;
    }
  }

  logger.printTrace('Unable to determine valid Gradle version range for Java version $javaV.');
  return null;
}

/// Validate that the specified Java and Android Gradle Plugin (AGP) versions are
/// compatible with each other.
///
/// Returns true when the specified Java and AGP versions are
/// definitely compatible; otherwise, false is assumed by default. In addition,
/// this will return false when either a null Java or AGP version is provided.
///
/// Source of truth are the AGP release notes:
/// https://developer.android.com/build/releases/gradle-plugin
bool validateJavaAndAgp(Logger logger,
    {required String? javaV, required String? agpV}) {
  if (javaV == null || agpV == null) {
    logger.printTrace(
        'Java version or AGP version unknown ($javaV, $agpV).');
    return false;
  }

  // Check if AGP version is too old to perform validation.
  if (isWithinVersionRange(agpV,
      min: '1.0', max: oldestDocumentedJavaAgpCompatibilityVersion, inclusiveMax: false)) {
    logger.printTrace('AGP Version: $agpV is too old to determine Java compatibility.');
    return false;
  }

  if (isWithinVersionRange(agpV,
        min: maxKnownAndSupportedAgpVersion, max: '100.100', inclusiveMin: false)) {
    logger.printTrace('AGP Version: $agpV is too new to determine Java compatibility.');
    return false;
  }

  // Begin known Java <-> AGP evaluation.
  for (final JavaAgpCompat data in _javaAgpCompatList) {
    if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) {
      return isWithinVersionRange(javaV, min: data.javaMin, max: '100.100');
    }
  }

  logger.printTrace('Unknown Java-AGP compatibility $javaV, $agpV');
  return false;
  }

  /// Returns compatibility information concerning the minimum AGP
  /// version for the specified Java version.
  JavaAgpCompat? getMinimumAgpVersionForJavaVersion(Logger logger,
    {required String javaV}) {
  for (final JavaAgpCompat data in _javaAgpCompatList) {
    if (isWithinVersionRange(javaV, min: data.javaMin, max: '100.100')) {
      return data;
    }
  }

  logger.printTrace('Unable to determine minimum AGP version for specified Java version.');
  return null;
}

648
/// Returns valid Java range for specified Gradle and AGP versions.
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
///
/// Assumes that gradleV and agpV are compatible versions.
VersionRange getJavaVersionFor({required String gradleV, required String agpV}) {
  // Find minimum Java version based on AGP compatibility.
  String? minJavaVersion;
  for (final JavaAgpCompat data in _javaAgpCompatList) {
    if (isWithinVersionRange(agpV, min: data.agpMin, max: data.agpMax)) {
      minJavaVersion = data.javaMin;
    }
  }

  // Find maximum Java version based on Gradle compatibility.
  String? maxJavaVersion;
  for (final JavaGradleCompat data in _javaGradleCompatList.reversed) {
    if (isWithinVersionRange(gradleV, min: data.gradleMin, max: maxKnownAndSupportedGradleVersion)) {
      maxJavaVersion = data.javaMax;
    }
  }

  return VersionRange(minJavaVersion, maxJavaVersion);
}

671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
/// Returns the Gradle version that is required by the given Android Gradle plugin version
/// by picking the largest compatible version from
/// https://developer.android.com/studio/releases/gradle-plugin#updating-gradle
String getGradleVersionFor(String androidPluginVersion) {
  final List<GradleForAgp> compatList = <GradleForAgp> [
    GradleForAgp(agpMin: '1.0.0', agpMax: '1.1.3', minRequiredGradle: '2.3'),
    GradleForAgp(agpMin: '1.2.0', agpMax: '1.3.1', minRequiredGradle: '2.9'),
    GradleForAgp(agpMin: '1.5.0', agpMax: '1.5.0', minRequiredGradle: '2.2.1'),
    GradleForAgp(agpMin: '2.0.0', agpMax: '2.1.2', minRequiredGradle: '2.13'),
    GradleForAgp(agpMin: '2.1.3', agpMax: '2.2.3', minRequiredGradle: '2.14.1'),
    GradleForAgp(agpMin: '2.3.0', agpMax: '2.9.9', minRequiredGradle: '3.3'),
    GradleForAgp(agpMin: '3.0.0', agpMax: '3.0.9', minRequiredGradle: '4.1'),
    GradleForAgp(agpMin: '3.1.0', agpMax: '3.1.9', minRequiredGradle: '4.4'),
    GradleForAgp(agpMin: '3.2.0', agpMax: '3.2.1', minRequiredGradle: '4.6'),
    GradleForAgp(agpMin: '3.3.0', agpMax: '3.3.2', minRequiredGradle: '4.10.2'),
    GradleForAgp(agpMin: '3.4.0', agpMax: '3.5.0', minRequiredGradle: '5.6.2'),
    GradleForAgp(agpMin: '4.0.0', agpMax: '4.1.0', minRequiredGradle: '6.7'),
    // 7.5 is a made up value to include everything through 7.4.*
    GradleForAgp(agpMin: '7.0.0', agpMax: '7.5', minRequiredGradle: '7.5'),
    GradleForAgp(agpMin: '7.5.0', agpMax:  '100.100', minRequiredGradle: '8.0'),
  // Assume if AGP is newer than this code know about return the highest gradle
  // version we know about.
693
    GradleForAgp(agpMin: maxKnownAgpVersion, agpMax: maxKnownAgpVersion, minRequiredGradle: maxKnownAndSupportedGradleVersion),
694 695 696 697 698 699 700


  ];
  for (final GradleForAgp data in compatList) {
    if (isWithinVersionRange(androidPluginVersion, min: data.agpMin, max: data.agpMax)) {
      return data.minRequiredGradle;
    }
701
  }
702
  if (isWithinVersionRange(androidPluginVersion, min: maxKnownAgpVersion, max: '100.100')) {
703
    return maxKnownAndSupportedGradleVersion;
704
  }
705
  throwToolExit('Unsupported Android Plugin version: $androidPluginVersion.');
706 707 708 709 710 711 712 713
}

/// Overwrite local.properties in the specified Flutter project's Android
/// sub-project, if needed.
///
/// If [requireAndroidSdk] is true (the default) and no Android SDK is found,
/// this will fail with a [ToolExit].
void updateLocalProperties({
714 715
  required FlutterProject project,
  BuildInfo? buildInfo,
716 717
  bool requireAndroidSdk = true,
}) {
718
  if (requireAndroidSdk && globals.androidSdk == null) {
719 720 721 722 723 724 725 726 727 728 729 730 731
    exitWithNoSdkMessage();
  }
  final File localProperties = project.android.localPropertiesFile;
  bool changed = false;

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

732
  void changeIfNecessary(String key, String? value) {
733 734 735 736 737 738 739 740 741 742 743
    if (settings.values[key] == value) {
      return;
    }
    if (value == null) {
      settings.values.remove(key);
    } else {
      settings.values[key] = value;
    }
    changed = true;
  }

744
  final AndroidSdk? androidSdk = globals.androidSdk;
745 746
  if (androidSdk != null) {
    changeIfNecessary('sdk.dir', globals.fsUtils.escapePath(androidSdk.directory.path));
747 748
  }

749
  changeIfNecessary('flutter.sdk', globals.fsUtils.escapePath(Cache.flutterRoot!));
750 751
  if (buildInfo != null) {
    changeIfNecessary('flutter.buildMode', buildInfo.modeName);
752
    final String? buildName = validatedBuildNameForPlatform(
753 754
      TargetPlatform.android_arm,
      buildInfo.buildName ?? project.manifest.buildName,
755
      globals.logger,
756 757
    );
    changeIfNecessary('flutter.versionName', buildName);
758
    final String? buildNumber = validatedBuildNumberForPlatform(
759 760
      TargetPlatform.android_arm,
      buildInfo.buildNumber ?? project.manifest.buildNumber,
761
      globals.logger,
762
    );
763
    changeIfNecessary('flutter.versionCode', buildNumber);
764 765 766 767 768 769 770 771 772 773 774 775
  }

  if (changed) {
    settings.writeContents(localProperties);
  }
}

/// Writes standard Android local properties to the specified [properties] file.
///
/// Writes the path to the Android SDK, if known.
void writeLocalProperties(File properties) {
  final SettingsFile settings = SettingsFile();
776
  final AndroidSdk? androidSdk = globals.androidSdk;
777 778
  if (androidSdk != null) {
    settings.values['sdk.dir'] = globals.fsUtils.escapePath(androidSdk.directory.path);
779 780 781 782 783
  }
  settings.writeContents(properties);
}

void exitWithNoSdkMessage() {
784 785 786 787 788
  BuildEvent('unsupported-project',
          type: 'gradle',
          eventError: 'android-sdk-not-found',
          flutterUsage: globals.flutterUsage)
      .send();
789 790 791 792 793
  globals.analytics.send(Event.flutterBuildInfo(
    label: 'unsupported-project',
    buildType: 'gradle',
    error: 'android-sdk-not-found',
  ));
794
  throwToolExit('${globals.logger.terminal.warningMark} No Android SDK found. '
795
      'Try setting the ANDROID_HOME environment variable.');
796 797
}

798
// Data class to hold normal/defined Java <-> Gradle compatibility criteria.
799 800 801 802
//
// The [javaMax] is exclusive in terms of supporting the noted [gradleMin],
// whereas [javaMin] is inclusive.
@immutable
803
class JavaGradleCompat {
804
  const JavaGradleCompat({
805 806 807 808 809
    required this.javaMin,
    required this.javaMax,
    required this.gradleMin,
    required this.gradleMax,
  });
810

811 812 813 814
  final String javaMin;
  final String javaMax;
  final String gradleMin;
  final String gradleMax;
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

  @override
  bool operator ==(Object other) =>
      other is JavaGradleCompat &&
      other.javaMin == javaMin &&
      other.javaMax == javaMax &&
      other.gradleMin == gradleMin &&
      other.gradleMax == gradleMax;

  @override
  int get hashCode => Object.hash(javaMin, javaMax, gradleMin, gradleMax);
}

// Data class to hold defined Java <-> AGP compatibility criteria.
//
// The [agpMin] and [agpMax] are inclusive in terms of having the
// noted [javaMin] and [javaDefault] versions.
@immutable
class JavaAgpCompat {
  const JavaAgpCompat({
    required this.javaMin,
    required this.javaDefault,
    required this.agpMin,
    required this.agpMax,
  });

  final String javaMin;
  final String javaDefault;
  final String agpMin;
  final String agpMax;

  @override
  bool operator ==(Object other) =>
      other is JavaAgpCompat &&
      other.javaMin == javaMin &&
      other.javaDefault == javaDefault &&
      other.agpMin == agpMin &&
      other.agpMax == agpMax;

  @override
  int get hashCode => Object.hash(javaMin, javaDefault, agpMin, agpMax);
856 857 858 859 860 861 862 863
}

class GradleForAgp {
  GradleForAgp({
    required this.agpMin,
    required this.agpMax,
    required this.minRequiredGradle,
  });
864

865 866 867
  final String agpMin;
  final String agpMax;
  final String minRequiredGradle;
868
}
869 870 871 872 873 874 875 876 877

// Returns gradlew file name based on the platform.
String getGradlewFileName(Platform platform) {
  if (platform.isWindows) {
    return 'gradlew.bat';
  } else {
    return 'gradlew';
  }
}
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986

/// List of compatible Java/Gradle versions.
///
/// Should be updated when a new version of Java is supported by a new version
/// of Gradle, as https://docs.gradle.org/current/userguide/compatibility.html
/// details.
List<JavaGradleCompat> _javaGradleCompatList = const <JavaGradleCompat>[
    JavaGradleCompat(
      javaMin: '19',
      javaMax: '20',
      gradleMin: '7.6',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '18',
      javaMax: '19',
      gradleMin: '7.5',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '17',
      javaMax: '18',
      gradleMin: '7.3',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '16',
      javaMax: '17',
      gradleMin: '7.0',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '15',
      javaMax: '16',
      gradleMin: '6.7',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '14',
      javaMax: '15',
      gradleMin: '6.3',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '13',
      javaMax: '14',
      gradleMin: '6.0',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '12',
      javaMax: '13',
      gradleMin: '5.4',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '11',
      javaMax: '12',
      gradleMin: '5.0',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    // 1.11 is a made up java version to cover everything in 1.10.*
    JavaGradleCompat(
      javaMin: '1.10',
      javaMax: '1.11',
      gradleMin: '4.7',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '1.9',
      javaMax: '1.10',
      gradleMin: '4.3',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
    JavaGradleCompat(
      javaMin: '1.8',
      javaMax: '1.9',
      gradleMin: '2.0',
      gradleMax: maxKnownAndSupportedGradleVersion,
    ),
  ];

  // List of compatible Java/AGP versions, where agpMax versions are inclusive.
  //
  // Should be updated whenever a new version of AGP is released as
  // https://developer.android.com/build/releases/gradle-plugin details.
  List<JavaAgpCompat> _javaAgpCompatList = const <JavaAgpCompat>[
    JavaAgpCompat(
      javaMin: '17',
      javaDefault: '17',
      agpMin: '8.0',
      agpMax: maxKnownAndSupportedAgpVersion,
    ),
    JavaAgpCompat(
      javaMin: '11',
      javaDefault: '11',
      agpMin: '7.0',
      agpMax: '7.4',
    ),
    JavaAgpCompat(
      // You may use JDK 1.7 with AGP 4.2, but we treat 1.8 as the default since
      // it is used by default for this AGP version and lower versions of Java
      // are deprecated for executing Gradle.
      javaMin: '1.8',
      javaDefault: '1.8',
      agpMin: '4.2',
      agpMax: '4.2',
    ),
  ];