[tools] use Java class for all java-searching behavior (#127354)
Fixes #124252, finishing work on the umbrella tracking issue, #126126. Essentially, after this PR, no (non-test) code should be be referencing/invoking the java home or binary paths.
This commit is contained in:
@@ -38,7 +38,6 @@ class AndroidSdk {
|
||||
reinitialize();
|
||||
}
|
||||
|
||||
static const String javaHomeEnvironmentVariable = 'JAVA_HOME';
|
||||
/// The Android SDK root directory.
|
||||
final Directory directory;
|
||||
|
||||
|
||||
@@ -28,18 +28,6 @@ import 'android_studio_validator.dart';
|
||||
final RegExp _dotHomeStudioVersionMatcher =
|
||||
RegExp(r'^\.?(AndroidStudio[^\d]*)([\d.]+)');
|
||||
|
||||
// TODO(andrewkolos): this global variable is used in several places to provide
|
||||
// a java binary to multiple Java-dependent tools, including the Android SDK
|
||||
// and Gradle. If this is null, these tools will implicitly fall back to current
|
||||
// JAVA_HOME env variable and then to any java found on PATH.
|
||||
//
|
||||
// This logic is consistent with that used by flutter doctor to find a valid JDK,
|
||||
// but this consistency is fragile--the implementations of this logic
|
||||
// exist independently of each other.
|
||||
//
|
||||
// See https://github.com/flutter/flutter/issues/124252.
|
||||
String? get javaPath => globals.androidStudio?.javaPath;
|
||||
|
||||
class AndroidStudio {
|
||||
/// A [version] value of null represents an unknown version.
|
||||
AndroidStudio(
|
||||
@@ -173,6 +161,9 @@ class AndroidStudio {
|
||||
/// The path of the JDK bundled with Android Studio.
|
||||
///
|
||||
/// This will be null if the bundled JDK could not be found or run.
|
||||
///
|
||||
/// If you looking to invoke the java binary or add it to the system
|
||||
/// environment variables, consider using the [Java] class instead.
|
||||
String? get javaPath => _javaPath;
|
||||
|
||||
bool get isValid => _isValid;
|
||||
|
||||
@@ -75,84 +75,58 @@ class AndroidWorkflow implements Workflow {
|
||||
/// Android Studio.
|
||||
class AndroidValidator extends DoctorValidator {
|
||||
AndroidValidator({
|
||||
required Java? java,
|
||||
required AndroidSdk? androidSdk,
|
||||
required AndroidStudio? androidStudio,
|
||||
required FileSystem fileSystem,
|
||||
required Logger logger,
|
||||
required Platform platform,
|
||||
required ProcessManager processManager,
|
||||
required UserMessages userMessages,
|
||||
}) : _androidSdk = androidSdk,
|
||||
_androidStudio = androidStudio,
|
||||
_fileSystem = fileSystem,
|
||||
}) : _java = java,
|
||||
_androidSdk = androidSdk,
|
||||
_logger = logger,
|
||||
_platform = platform,
|
||||
_processManager = processManager,
|
||||
_userMessages = userMessages,
|
||||
super('Android toolchain - develop for Android devices');
|
||||
|
||||
final Java? _java;
|
||||
final AndroidSdk? _androidSdk;
|
||||
final AndroidStudio? _androidStudio;
|
||||
final FileSystem _fileSystem;
|
||||
final Logger _logger;
|
||||
final Platform _platform;
|
||||
final ProcessManager _processManager;
|
||||
final UserMessages _userMessages;
|
||||
|
||||
@override
|
||||
String get slowWarning => '${_task ?? 'This'} is taking a long time...';
|
||||
String? _task;
|
||||
|
||||
/// Finds the semantic version anywhere in a text.
|
||||
static final RegExp _javaVersionPattern = RegExp(r'(\d+)(\.(\d+)(\.(\d+))?)?');
|
||||
|
||||
/// `java -version` response is not only a number, but also includes other
|
||||
/// information eg. `openjdk version "1.7.0_212"`.
|
||||
/// This method extracts only the semantic version from that response.
|
||||
static String? _extractJavaVersion(String? text) {
|
||||
if (text == null || text.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final Match? match = _javaVersionPattern.firstMatch(text);
|
||||
if (match == null) {
|
||||
return null;
|
||||
}
|
||||
return text.substring(match.start, match.end);
|
||||
}
|
||||
|
||||
/// Returns false if we cannot determine the Java version or if the version
|
||||
/// is older that the minimum allowed version of 1.8.
|
||||
Future<bool> _checkJavaVersion(String javaBinary, List<ValidationMessage> messages) async {
|
||||
Future<bool> _checkJavaVersion(List<ValidationMessage> messages) async {
|
||||
_task = 'Checking Java status';
|
||||
try {
|
||||
if (!_processManager.canRun(javaBinary)) {
|
||||
messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(javaBinary)));
|
||||
if (_java?.binaryPath == null) {
|
||||
messages.add(ValidationMessage.error(_userMessages.androidMissingJdk));
|
||||
return false;
|
||||
}
|
||||
String? javaVersionText;
|
||||
messages.add(ValidationMessage(_userMessages.androidJdkLocation(_java!.binaryPath)));
|
||||
if (!_java!.canRun()) {
|
||||
messages.add(ValidationMessage.error(_userMessages.androidCantRunJavaBinary(_java!.binaryPath)));
|
||||
return false;
|
||||
}
|
||||
Version? javaVersion;
|
||||
try {
|
||||
// TODO(andrewkolos): Use Java class to find version instead of using duplicate
|
||||
// code. See https://github.com/flutter/flutter/issues/124252.
|
||||
_logger.printTrace('java -version');
|
||||
final ProcessResult result = await _processManager.run(<String>[javaBinary, '-version']);
|
||||
if (result.exitCode == 0) {
|
||||
final List<String> versionLines = (result.stderr as String).split('\n');
|
||||
javaVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
|
||||
}
|
||||
javaVersion = _java!.version;
|
||||
} on Exception catch (error) {
|
||||
_logger.printTrace(error.toString());
|
||||
}
|
||||
final Version? javaVersion = Version.parse(_extractJavaVersion(javaVersionText));
|
||||
if (javaVersionText == null || javaVersionText.isEmpty || javaVersion == null) {
|
||||
if (javaVersion == null) {
|
||||
// Could not determine the java version.
|
||||
messages.add(ValidationMessage.error(_userMessages.androidUnknownJavaVersion));
|
||||
return false;
|
||||
}
|
||||
if (javaVersion < kAndroidJavaMinVersion) {
|
||||
messages.add(ValidationMessage.error(_userMessages.androidJavaMinimumVersion(javaVersionText)));
|
||||
messages.add(ValidationMessage.error(_userMessages.androidJavaMinimumVersion(javaVersion.toString())));
|
||||
return false;
|
||||
}
|
||||
messages.add(ValidationMessage(_userMessages.androidJavaVersion(javaVersionText)));
|
||||
messages.add(ValidationMessage(_userMessages.androidJavaVersion(javaVersion.toString())));
|
||||
return true;
|
||||
} finally {
|
||||
_task = null;
|
||||
@@ -234,22 +208,9 @@ class AndroidValidator extends DoctorValidator {
|
||||
}
|
||||
|
||||
_task = 'Finding Java binary';
|
||||
// Now check for the JDK.
|
||||
final String? javaBinary = Java.find(
|
||||
logger: _logger,
|
||||
androidStudio: _androidStudio,
|
||||
fileSystem: _fileSystem,
|
||||
platform: _platform,
|
||||
processManager: _processManager,
|
||||
)?.binaryPath;
|
||||
if (javaBinary == null) {
|
||||
messages.add(ValidationMessage.error(_userMessages.androidMissingJdk));
|
||||
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
|
||||
}
|
||||
messages.add(ValidationMessage(_userMessages.androidJdkLocation(javaBinary)));
|
||||
|
||||
// Check JDK version.
|
||||
if (!await _checkJavaVersion(javaBinary, messages)) {
|
||||
if (!await _checkJavaVersion(messages)) {
|
||||
return ValidationResult(ValidationType.partial, messages, statusInfo: sdkVersionText);
|
||||
}
|
||||
|
||||
|
||||
@@ -30,10 +30,10 @@ import '../globals.dart' as globals;
|
||||
import '../project.dart';
|
||||
import '../reporting/reporting.dart';
|
||||
import 'android_builder.dart';
|
||||
import 'android_sdk.dart';
|
||||
import 'android_studio.dart';
|
||||
import 'gradle_errors.dart';
|
||||
import 'gradle_utils.dart';
|
||||
import 'java.dart';
|
||||
import 'migrations/android_studio_java_gradle_conflict_migration.dart';
|
||||
import 'migrations/top_level_gradle_build_file_migration.dart';
|
||||
import 'multidex.dart';
|
||||
@@ -132,6 +132,7 @@ const Duration kMaxRetryTime = Duration(seconds: 10);
|
||||
/// An implementation of the [AndroidBuilder] that delegates to gradle.
|
||||
class AndroidGradleBuilder implements AndroidBuilder {
|
||||
AndroidGradleBuilder({
|
||||
required Java? java,
|
||||
required Logger logger,
|
||||
required ProcessManager processManager,
|
||||
required FileSystem fileSystem,
|
||||
@@ -140,7 +141,8 @@ class AndroidGradleBuilder implements AndroidBuilder {
|
||||
required GradleUtils gradleUtils,
|
||||
required Platform platform,
|
||||
required AndroidStudio? androidStudio,
|
||||
}) : _logger = logger,
|
||||
}) : _java = java,
|
||||
_logger = logger,
|
||||
_fileSystem = fileSystem,
|
||||
_artifacts = artifacts,
|
||||
_usage = usage,
|
||||
@@ -149,6 +151,7 @@ class AndroidGradleBuilder implements AndroidBuilder {
|
||||
_fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform),
|
||||
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
|
||||
|
||||
final Java? _java;
|
||||
final Logger _logger;
|
||||
final ProcessUtils _processUtils;
|
||||
final FileSystem _fileSystem;
|
||||
@@ -422,15 +425,11 @@ class AndroidGradleBuilder implements AndroidBuilder {
|
||||
..start();
|
||||
int exitCode = 1;
|
||||
try {
|
||||
final String? javaHome = globals.java?.javaHome;
|
||||
exitCode = await _processUtils.stream(
|
||||
command,
|
||||
workingDirectory: project.android.hostAppGradleRoot.path,
|
||||
allowReentrantFlutter: true,
|
||||
environment: <String, String>{
|
||||
if (javaHome != null)
|
||||
AndroidSdk.javaHomeEnvironmentVariable: javaHome,
|
||||
},
|
||||
environment: _java?.environment,
|
||||
mapFunction: consumeLog,
|
||||
);
|
||||
} on ProcessException catch (exception) {
|
||||
@@ -692,15 +691,11 @@ class AndroidGradleBuilder implements AndroidBuilder {
|
||||
..start();
|
||||
RunResult result;
|
||||
try {
|
||||
final String? javaHome = globals.java?.javaHome;
|
||||
result = await _processUtils.run(
|
||||
command,
|
||||
workingDirectory: project.android.hostAppGradleRoot.path,
|
||||
allowReentrantFlutter: true,
|
||||
environment: <String, String>{
|
||||
if (javaHome != null)
|
||||
AndroidSdk.javaHomeEnvironmentVariable: javaHome,
|
||||
},
|
||||
environment: _java?.environment,
|
||||
);
|
||||
} finally {
|
||||
status.stop();
|
||||
@@ -745,15 +740,11 @@ class AndroidGradleBuilder implements AndroidBuilder {
|
||||
..start();
|
||||
RunResult result;
|
||||
try {
|
||||
final String? javaHome = globals.java?.javaHome;
|
||||
result = await _processUtils.run(
|
||||
command,
|
||||
workingDirectory: project.android.hostAppGradleRoot.path,
|
||||
allowReentrantFlutter: true,
|
||||
environment: <String, String>{
|
||||
if (javaHome != null)
|
||||
AndroidSdk.javaHomeEnvironmentVariable: javaHome,
|
||||
},
|
||||
environment: _java?.environment,
|
||||
);
|
||||
} finally {
|
||||
status.stop();
|
||||
|
||||
@@ -11,8 +11,6 @@ import '../base/terminal.dart';
|
||||
import '../globals.dart' as globals;
|
||||
import '../project.dart';
|
||||
import '../reporting/reporting.dart';
|
||||
import 'android_sdk.dart';
|
||||
import 'android_studio.dart';
|
||||
import 'gradle_utils.dart';
|
||||
import 'multidex.dart';
|
||||
|
||||
@@ -379,10 +377,7 @@ final GradleHandledError flavorUndefinedHandler = GradleHandledError(
|
||||
],
|
||||
throwOnError: true,
|
||||
workingDirectory: project.android.hostAppGradleRoot.path,
|
||||
environment: <String, String>{
|
||||
if (javaPath != null)
|
||||
AndroidSdk.javaHomeEnvironmentVariable: javaPath!,
|
||||
},
|
||||
environment: globals.java?.environment,
|
||||
);
|
||||
// Extract build types and product flavors.
|
||||
final Set<String> variants = <String>{};
|
||||
|
||||
@@ -9,13 +9,14 @@ import '../base/logger.dart';
|
||||
import '../base/os.dart';
|
||||
import '../base/platform.dart';
|
||||
import '../base/process.dart';
|
||||
import '../base/version.dart';
|
||||
import 'android_studio.dart';
|
||||
|
||||
const String _javaHomeEnvironmentVariable = 'JAVA_HOME';
|
||||
const String _kJavaExecutable = 'java';
|
||||
const String _javaExecutable = 'java';
|
||||
|
||||
/// Represents an installation of Java.
|
||||
class Java {
|
||||
|
||||
Java({
|
||||
required this.javaHome,
|
||||
required this.binaryPath,
|
||||
@@ -31,6 +32,15 @@ class Java {
|
||||
_processManager = processManager,
|
||||
_processUtils = ProcessUtils(processManager: processManager, logger: logger);
|
||||
|
||||
/// Within the Java ecosystem, this environment variable is typically set
|
||||
/// the install location of a Java Runtime Environment (JRE) or Java
|
||||
/// Development Kit (JDK).
|
||||
///
|
||||
/// Tools that depend on Java and need to find it will often check this
|
||||
/// variable. If you are looking to set `JAVA_HOME` when stating a process,
|
||||
/// consider using the [environment] instance property instead.
|
||||
static String javaHomeEnvironmentVariable = 'JAVA_HOME';
|
||||
|
||||
/// Finds the Java runtime environment that should be used for all java-dependent
|
||||
/// operations across the tool.
|
||||
///
|
||||
@@ -41,13 +51,6 @@ class Java {
|
||||
/// 3. the java binary found on PATH.
|
||||
///
|
||||
/// Returns null if no java binary could be found.
|
||||
// TODO(andrewkolos): To prevent confusion when debugging Android-related
|
||||
// issues (see https://github.com/flutter/flutter/issues/122609 for an example),
|
||||
// this logic should be consistently followed by any Java-dependent operation
|
||||
// across the the tool (building Android apps, interacting with the Android SDK, etc.).
|
||||
// Currently, this consistency is fragile since the logic used for building
|
||||
// Android apps exists independently of this method.
|
||||
// See https://github.com/flutter/flutter/issues/124252.
|
||||
static Java? find({
|
||||
required AndroidStudio? androidStudio,
|
||||
required Logger logger,
|
||||
@@ -89,7 +92,7 @@ class Java {
|
||||
);
|
||||
}
|
||||
|
||||
/// The path of the runtime's home directory.
|
||||
/// The path of the runtime environments' home directory.
|
||||
///
|
||||
/// This should only be used for logging and validation purposes.
|
||||
/// If you need to set JAVA_HOME when starting a process, consider
|
||||
@@ -98,7 +101,7 @@ class Java {
|
||||
/// a new method to this class instead.
|
||||
final String? javaHome;
|
||||
|
||||
/// The path of the runtime's java binary.
|
||||
/// The path of the runtime environments' java binary.
|
||||
///
|
||||
/// This should be only used for logging and validation purposes.
|
||||
/// If you need to invoke the binary directly, consider adding a new method
|
||||
@@ -120,7 +123,7 @@ class Java {
|
||||
/// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.)
|
||||
Map<String, String> get environment {
|
||||
return <String, String>{
|
||||
if (javaHome != null) _javaHomeEnvironmentVariable: javaHome!,
|
||||
if (javaHome != null) javaHomeEnvironmentVariable: javaHome!,
|
||||
'PATH': _fileSystem.path.dirname(binaryPath) +
|
||||
_os.pathVarSeparator +
|
||||
_platform.environment['PATH']!,
|
||||
@@ -129,7 +132,7 @@ class Java {
|
||||
|
||||
/// Returns the version of java in the format \d(.\d)+(.\d)+
|
||||
/// Returns null if version could not be determined.
|
||||
late final JavaVersion? version = (() {
|
||||
late final Version? version = (() {
|
||||
final RunResult result = _processUtils.runSync(
|
||||
<String>[binaryPath, '--version'],
|
||||
environment: environment,
|
||||
@@ -138,7 +141,38 @@ class Java {
|
||||
_logger.printTrace('java --version failed: exitCode: ${result.exitCode}'
|
||||
' stdout: ${result.stdout} stderr: ${result.stderr}');
|
||||
}
|
||||
return JavaVersion.tryParseFromJavaOutput(result.stdout, logger: _logger);
|
||||
final String rawVersionOutput = result.stdout;
|
||||
final List<String> versionLines = rawVersionOutput.split('\n');
|
||||
// Should look something like 'openjdk 19.0.2 2023-01-17'.
|
||||
final String longVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
|
||||
|
||||
// The contents that matter come in the format '11.0.18' or '1.8.0_202'.
|
||||
final RegExp jdkVersionRegex = RegExp(r'\d+\.\d+(\.\d+(?:_\d+)?)?');
|
||||
final Iterable<RegExpMatch> matches =
|
||||
jdkVersionRegex.allMatches(rawVersionOutput);
|
||||
if (matches.isEmpty) {
|
||||
_logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
|
||||
return null;
|
||||
}
|
||||
final String? version = matches.first.group(0);
|
||||
if (version == null || version.split('_').isEmpty) {
|
||||
_logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
|
||||
return null;
|
||||
}
|
||||
|
||||
// Trim away _d+ from versions 1.8 and below.
|
||||
final String versionWithoutBuildInfo = version.split('_').first;
|
||||
|
||||
final Version? parsedVersion = Version.parse(versionWithoutBuildInfo);
|
||||
if (parsedVersion == null) {
|
||||
return null;
|
||||
}
|
||||
return Version.withText(
|
||||
parsedVersion.major,
|
||||
parsedVersion.minor,
|
||||
parsedVersion.patch,
|
||||
longVersionText,
|
||||
);
|
||||
})();
|
||||
|
||||
bool canRun() {
|
||||
@@ -156,7 +190,7 @@ String? _findJavaHome({
|
||||
return androidStudioJavaPath;
|
||||
}
|
||||
|
||||
final String? javaHomeEnv = platform.environment[_javaHomeEnvironmentVariable];
|
||||
final String? javaHomeEnv = platform.environment[Java.javaHomeEnvironmentVariable];
|
||||
if (javaHomeEnv != null) {
|
||||
return javaHomeEnv;
|
||||
}
|
||||
@@ -175,7 +209,7 @@ String? _findJavaBinary({
|
||||
}
|
||||
|
||||
// Fallback to PATH based lookup.
|
||||
return operatingSystemUtils.which(_kJavaExecutable)?.path;
|
||||
return operatingSystemUtils.which(_javaExecutable)?.path;
|
||||
}
|
||||
|
||||
// Returns a user visible String that says the tool failed to parse
|
||||
@@ -187,44 +221,3 @@ String _formatJavaVersionWarning(String javaVersionRaw) {
|
||||
'https://github.com/flutter/flutter/issues/ '
|
||||
'and if one does not exist file a new issue.';
|
||||
}
|
||||
|
||||
class JavaVersion {
|
||||
JavaVersion({
|
||||
required this.longText,
|
||||
required this.number
|
||||
});
|
||||
|
||||
/// Typically the first line of the output from `java --version`.
|
||||
/// For example, `"openjdk 19.0.2 2023-01-17"`.
|
||||
final String longText;
|
||||
|
||||
/// The version number. For example, `"19.0.2."`.
|
||||
final String number;
|
||||
|
||||
/// Extracts JDK version from the output of java --version.
|
||||
static JavaVersion? tryParseFromJavaOutput(String rawVersionOutput, {
|
||||
required Logger logger,
|
||||
}) {
|
||||
final List<String> versionLines = rawVersionOutput.split('\n');
|
||||
final String longText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
|
||||
|
||||
// The contents that matter come in the format '11.0.18' or '1.8.0_202'.
|
||||
final RegExp jdkVersionRegex = RegExp(r'\d+\.\d+(\.\d+(?:_\d+)?)?');
|
||||
final Iterable<RegExpMatch> matches =
|
||||
jdkVersionRegex.allMatches(rawVersionOutput);
|
||||
if (matches.isEmpty) {
|
||||
logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
|
||||
return null;
|
||||
}
|
||||
final String? rawShortText = matches.first.group(0);
|
||||
if (rawShortText == null || rawShortText.split('_').isEmpty) {
|
||||
logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
|
||||
return null;
|
||||
}
|
||||
|
||||
// Trim away _d+ from versions 1.8 and below.
|
||||
final String shortText = rawShortText.split('_').first;
|
||||
|
||||
return JavaVersion(longText: longText, number: shortText);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,14 +99,12 @@ class AndroidStudioJavaGradleConflictMigration extends ProjectMigrator {
|
||||
return;
|
||||
}
|
||||
|
||||
final String? javaVersionString = _java?.version?.number;
|
||||
final Version? javaVersion = Version.parse(javaVersionString);
|
||||
if (javaVersion == null) {
|
||||
if (_java?.version == null) {
|
||||
logger.printTrace(javaVersionNotFound);
|
||||
return;
|
||||
}
|
||||
|
||||
if (javaVersion.major != flamingoBundledJava.major) {
|
||||
if (_java!.version!.major != flamingoBundledJava.major) {
|
||||
logger.printTrace(javaVersionNot17);
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user