java.dart 8.04 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter 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 'package:process/process.dart';

7
import '../base/config.dart';
8 9 10 11 12
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/process.dart';
13
import '../base/version.dart';
14 15
import 'android_studio.dart';

16
const String _javaExecutable = 'java';
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/// Represents an installation of Java.
class Java {
  Java({
    required this.javaHome,
    required this.binaryPath,
    required Logger logger,
    required FileSystem fileSystem,
    required OperatingSystemUtils os,
    required Platform platform,
    required ProcessManager processManager,
  }): _logger = logger,
      _fileSystem = fileSystem,
      _os = os,
      _platform = platform,
      _processManager = processManager,
      _processUtils = ProcessUtils(processManager: processManager, logger: logger);

35 36 37 38 39 40 41 42 43
  /// 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';

44 45 46 47 48 49 50 51 52 53 54
  /// Finds the Java runtime environment that should be used for all java-dependent
  /// operations across the tool.
  ///
  /// This searches for Java in the following places, in order:
  ///
  /// 1. the runtime environment bundled with Android Studio;
  /// 2. the runtime environment found in the JAVA_HOME env variable, if set; or
  /// 3. the java binary found on PATH.
  ///
  /// Returns null if no java binary could be found.
  static Java? find({
55
    required Config config,
56 57 58 59 60 61 62 63 64 65 66 67 68
    required AndroidStudio? androidStudio,
    required Logger logger,
    required FileSystem fileSystem,
    required Platform platform,
    required ProcessManager processManager,
  }) {
    final OperatingSystemUtils os = OperatingSystemUtils(
      fileSystem: fileSystem,
      logger: logger,
      platform: platform,
      processManager: processManager
    );
    final String? home = _findJavaHome(
69
      config: config,
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
      logger: logger,
      androidStudio: androidStudio,
      platform: platform
    );
    final String? binary = _findJavaBinary(
      logger: logger,
      javaHome: home,
      fileSystem: fileSystem,
      operatingSystemUtils: os,
      platform: platform
    );

    if (binary == null) {
      return null;
    }

    return Java(
      javaHome: home,
      binaryPath: binary,
      logger: logger,
      fileSystem: fileSystem,
      os: os,
      platform: platform,
      processManager: processManager,
    );
  }

97
  /// The path of the runtime environments' home directory.
98 99 100 101 102 103 104 105
  ///
  /// This should only be used for logging and validation purposes.
  /// If you need to set JAVA_HOME when starting a process, consider
  /// using [environment] instead.
  /// If you need to inspect the files of the runtime, considering adding
  /// a new method to this class instead.
  final String? javaHome;

106
  /// The path of the runtime environments' java binary.
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
  ///
  /// This should be only used for logging and validation purposes.
  /// If you need to invoke the binary directly, consider adding a new method
  /// to this class instead.
  final String binaryPath;

  final Logger _logger;
  final FileSystem _fileSystem;
  final OperatingSystemUtils _os;
  final Platform _platform;
  final ProcessManager _processManager;
  final ProcessUtils _processUtils;

  /// Returns an environment variable map with
  /// 1. JAVA_HOME set if this object has a known home directory, and
  /// 2. The java binary folder appended onto PATH, if the binary location is known.
  ///
  /// This map should be used as the environment when invoking any Java-dependent
  /// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.)
  Map<String, String> get environment {
    return <String, String>{
128
      if (javaHome != null) javaHomeEnvironmentVariable: javaHome!,
129 130 131 132 133 134 135 136
      'PATH': _fileSystem.path.dirname(binaryPath) +
                        _os.pathVarSeparator +
                        _platform.environment['PATH']!,
    };
  }

  /// Returns the version of java in the format \d(.\d)+(.\d)+
  /// Returns null if version could not be determined.
137
  late final Version? version = (() {
138 139 140 141
    if (!canRun()) {
      return null;
    }

142 143 144 145 146 147 148
    final RunResult result = _processUtils.runSync(
      <String>[binaryPath, '--version'],
      environment: environment,
    );
    if (result.exitCode != 0) {
      _logger.printTrace('java --version failed: exitCode: ${result.exitCode}'
        ' stdout: ${result.stdout} stderr: ${result.stderr}');
149
      return null;
150
    }
151 152 153 154 155
    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];

156 157
    // The contents that matter come in the format '11.0.18', '1.8.0_202 or 21'.
    final RegExp jdkVersionRegex = RegExp(r'(?<version>\d+(\.\d+(\.\d+(?:_\d+)?)?)?)');
158 159 160
    final Iterable<RegExpMatch> matches =
        jdkVersionRegex.allMatches(rawVersionOutput);
    if (matches.isEmpty) {
161 162 163 164 165 166 167 168 169 170 171
      // Fallback to second string format like "java 21.0.1 2023-09-19 LTS"
      final RegExp secondJdkVersionRegex =
          RegExp(r'java\s+(?<version>\d+(\.\d+)?(\.\d+)?)\s+\d\d\d\d-\d\d-\d\d');
      final RegExpMatch? match = secondJdkVersionRegex.firstMatch(versionLines[0]);
      if (match != null) {
        final Version? parsedVersion = Version.parse(match.namedGroup('version'));
        if (parsedVersion == null) {
          return null;
        }
        return parsedVersion;
      }
172 173 174
      _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
      return null;
    }
175
    final String? version = matches.first.namedGroup('version');
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    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,
    );
194 195 196 197 198 199 200 201
  })();

  bool canRun() {
    return _processManager.canRun(binaryPath);
  }
}

String? _findJavaHome({
202
  required Config config,
203 204 205 206
  required Logger logger,
  required AndroidStudio? androidStudio,
  required Platform platform,
}) {
207 208 209 210 211
  final Object? configured = config.getValue('jdk-dir');
  if (configured != null) {
    return configured as String;
  }

212 213 214 215 216
  final String? androidStudioJavaPath = androidStudio?.javaPath;
  if (androidStudioJavaPath != null) {
    return androidStudioJavaPath;
  }

217
  final String? javaHomeEnv = platform.environment[Java.javaHomeEnvironmentVariable];
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
  if (javaHomeEnv != null) {
    return javaHomeEnv;
  }
  return null;
}

String? _findJavaBinary({
  required Logger logger,
  required String? javaHome,
  required FileSystem fileSystem,
  required OperatingSystemUtils operatingSystemUtils,
  required Platform platform,
}) {
  if (javaHome != null) {
    return fileSystem.path.join(javaHome, 'bin', 'java');
  }

  // Fallback to PATH based lookup.
236
  return operatingSystemUtils.which(_javaExecutable)?.path;
237 238 239 240 241 242 243 244 245 246 247
}

// Returns a user visible String that says the tool failed to parse
// the version of java along with the output.
String _formatJavaVersionWarning(String javaVersionRaw) {
  return 'Could not parse java version from: \n'
    '$javaVersionRaw \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.';
}