android_studio.dart 10.5 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2017 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 '../base/common.dart';
import '../base/context.dart';
import '../base/file_system.dart';
8
import '../base/io.dart';
9 10
import '../base/platform.dart';
import '../base/process_manager.dart';
11
import '../base/version.dart';
12
import '../globals.dart';
13 14
import '../ios/ios_workflow.dart';
import '../ios/plist_utils.dart' as plist;
15

16
AndroidStudio get androidStudio => context.get<AndroidStudio>();
17 18 19 20 21 22 23 24 25 26

// Android Studio layout:

// Linux/Windows:
// $HOME/.AndroidStudioX.Y/system/.home

// macOS:
// /Applications/Android Studio.app/Contents/
// $HOME/Applications/Android Studio.app/Contents/

27
final RegExp _dotHomeStudioVersionMatcher =
28
    RegExp(r'^\.(AndroidStudio[^\d]*)([\d.]+)');
29

30 31
String get javaPath => androidStudio?.javaPath;

32
class AndroidStudio implements Comparable<AndroidStudio> {
33 34 35 36 37 38 39
  AndroidStudio(
    this.directory, {
    Version version,
    this.configured,
    this.studioAppName = 'AndroidStudio',
    this.presetPluginsPath,
  }) : version = version ?? Version.unknown {
40 41 42 43
    _init();
  }

  factory AndroidStudio.fromMacOSBundle(String bundlePath) {
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    String studioPath = fs.path.join(bundlePath, 'Contents');
    String plistFile = fs.path.join(studioPath, 'Info.plist');
    String plistValue = iosWorkflow.getPlistValueFromFile(
      plistFile,
      null,
    );
    final RegExp _pathsSelectorMatcher = RegExp(r'"idea.paths.selector" = "[^;]+"');
    final RegExp _jetBrainsToolboxAppMatcher = RegExp(r'JetBrainsToolboxApp = "[^;]+"');
    // As AndroidStudio managed by JetBrainsToolbox could have a wrapper pointing to the real Android Studio.
    // Check if we've found a JetBrainsToolbox wrapper and deal with it properly.
    final String jetBrainsToolboxAppBundlePath = extractStudioPlistValueWithMatcher(plistValue, _jetBrainsToolboxAppMatcher);
    if (jetBrainsToolboxAppBundlePath != null) {
      studioPath = fs.path.join(jetBrainsToolboxAppBundlePath, 'Contents');
      plistFile = fs.path.join(studioPath, 'Info.plist');
      plistValue = iosWorkflow.getPlistValueFromFile(
        plistFile,
        null,
      );
    }

64 65 66 67 68
    final String versionString = iosWorkflow.getPlistValueFromFile(
      plistFile,
      plist.kCFBundleShortVersionStringKey,
    );

69 70
    Version version;
    if (versionString != null)
71
      version = Version.parse(versionString);
72

73 74 75 76 77
    final String pathsSelectorValue = extractStudioPlistValueWithMatcher(plistValue, _pathsSelectorMatcher);
    final String presetPluginsPath = pathsSelectorValue == null
        ? null
        : fs.path.join(homeDirPath, 'Library', 'Application Support', '$pathsSelectorValue');
    return AndroidStudio(studioPath, version: version, presetPluginsPath: presetPluginsPath);
78 79 80
  }

  factory AndroidStudio.fromHomeDot(Directory homeDotDir) {
81
    final Match versionMatch =
82 83 84 85
        _dotHomeStudioVersionMatcher.firstMatch(homeDotDir.basename);
    if (versionMatch?.groupCount != 2) {
      return null;
    }
86
    final Version version = Version.parse(versionMatch[2]);
87 88
    final String studioAppName = versionMatch[1];
    if (studioAppName == null || version == null) {
89 90
      return null;
    }
91 92 93 94 95 96
    String installPath;
    try {
      installPath = fs
          .file(fs.path.join(homeDotDir.path, 'system', '.home'))
          .readAsStringSync();
    } catch (e) {
97
      // ignored, installPath will be null, which is handled below
98 99
    }
    if (installPath != null && fs.isDirectorySync(installPath)) {
100 101 102 103 104
      return AndroidStudio(
          installPath,
          version: version,
          studioAppName: studioAppName,
      );
105 106 107 108
    }
    return null;
  }

109 110 111 112
  final String directory;
  final String studioAppName;
  final Version version;
  final String configured;
113
  final String presetPluginsPath;
114 115 116 117 118

  String _javaPath;
  bool _isValid = false;
  final List<String> _validationMessages = <String>[];

119 120
  String get javaPath => _javaPath;

121 122
  bool get isValid => _isValid;

123
  String get pluginsPath {
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    if (presetPluginsPath != null) {
      return presetPluginsPath;
    }
    final int major = version?.major;
    final int minor = version?.minor;
    if (platform.isMacOS) {
      return fs.path.join(
          homeDirPath,
          'Library',
          'Application Support',
          'AndroidStudio$major.$minor');
    } else {
      return fs.path.join(homeDirPath,
          '.$studioAppName$major.$minor',
          'config',
          'plugins');
140 141 142
    }
  }

143 144 145 146
  List<String> get validationMessages => _validationMessages;

  @override
  int compareTo(AndroidStudio other) {
147
    final int result = version.compareTo(other.version);
148 149 150 151 152 153 154
    if (result == 0)
      return directory.compareTo(other.directory);
    return result;
  }

  /// Locates the newest, valid version of Android Studio.
  static AndroidStudio latestValid() {
155
    final String configuredStudio = config.getValue('android-studio-dir');
156 157
    if (configuredStudio != null) {
      String configuredStudioPath = configuredStudio;
158
      if (platform.isMacOS && !configuredStudioPath.endsWith('Contents'))
159
        configuredStudioPath = fs.path.join(configuredStudioPath, 'Contents');
160
      return AndroidStudio(configuredStudioPath,
161 162 163 164
          configured: configuredStudio);
    }

    // Find all available Studio installations.
165
    final List<AndroidStudio> studios = allInstalled();
166 167 168 169 170 171 172 173 174 175 176 177
    if (studios.isEmpty) {
      return null;
    }
    studios.sort();
    return studios.lastWhere((AndroidStudio s) => s.isValid,
        orElse: () => null);
  }

  static List<AndroidStudio> allInstalled() =>
      platform.isMacOS ? _allMacOS() : _allLinuxOrWindows();

  static List<AndroidStudio> _allMacOS() {
178
    final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
179 180

    void _checkForStudio(String path) {
181 182
      if (!fs.isDirectorySync(path))
        return;
183
      try {
184
        final Iterable<Directory> directories = fs
185
            .directory(path)
186
            .listSync(followLinks: false)
187
            .whereType<Directory>();
188
        for (Directory directory in directories) {
189 190 191
          final String name = directory.basename;
          // An exact match, or something like 'Android Studio 3.0 Preview.app'.
          if (name.startsWith('Android Studio') && name.endsWith('.app')) {
192 193 194 195
            candidatePaths.add(directory);
          } else if (!directory.path.endsWith('.app')) {
            _checkForStudio(directory.path);
          }
196
        }
197 198
      } catch (e) {
        printTrace('Exception while looking for Android Studio: $e');
199 200 201 202 203 204
      }
    }

    _checkForStudio('/Applications');
    _checkForStudio(fs.path.join(homeDirPath, 'Applications'));

205
    final String configuredStudioDir = config.getValue('android-studio-dir');
206 207 208 209 210 211 212 213 214 215 216 217
    if (configuredStudioDir != null) {
      FileSystemEntity configuredStudio = fs.file(configuredStudioDir);
      if (configuredStudio.basename == 'Contents') {
        configuredStudio = configuredStudio.parent;
      }
      if (!candidatePaths
          .any((FileSystemEntity e) => e.path == configuredStudio.path)) {
        candidatePaths.add(configuredStudio);
      }
    }

    return candidatePaths
218
        .map<AndroidStudio>((FileSystemEntity e) => AndroidStudio.fromMacOSBundle(e.path))
219 220 221 222 223
        .where((AndroidStudio s) => s != null)
        .toList();
  }

  static List<AndroidStudio> _allLinuxOrWindows() {
224
    final List<AndroidStudio> studios = <AndroidStudio>[];
225

226
    bool _hasStudioAt(String path, { Version newerThan }) {
227
      return studios.any((AndroidStudio studio) {
228 229
        if (studio.directory != path)
          return false;
230 231 232 233 234 235 236
        if (newerThan != null) {
          return studio.version.compareTo(newerThan) >= 0;
        }
        return true;
      });
    }

237
    // Read all $HOME/.AndroidStudio*/system/.home files. There may be several
238
    // pointing to the same installation, so we grab only the latest one.
239
    if (fs.directory(homeDirPath).existsSync()) {
240
      for (FileSystemEntity entity in fs.directory(homeDirPath).listSync(followLinks: false)) {
241
        if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) {
242
          final AndroidStudio studio = AndroidStudio.fromHomeDot(entity);
243 244 245 246
          if (studio != null && !_hasStudioAt(studio.directory, newerThan: studio.version)) {
            studios.removeWhere((AndroidStudio other) => other.directory == studio.directory);
            studios.add(studio);
          }
247 248 249 250
        }
      }
    }

251
    final String configuredStudioDir = config.getValue('android-studio-dir');
252
    if (configuredStudioDir != null && !_hasStudioAt(configuredStudioDir)) {
253
      studios.add(AndroidStudio(configuredStudioDir,
254 255 256 257 258 259
          configured: configuredStudioDir));
    }

    if (platform.isLinux) {
      void _checkWellKnownPath(String path) {
        if (fs.isDirectorySync(path) && !_hasStudioAt(path)) {
260
          studios.add(AndroidStudio(path));
261 262 263 264 265 266 267 268 269 270
        }
      }

      // Add /opt/android-studio and $HOME/android-studio, if they exist.
      _checkWellKnownPath('/opt/android-studio');
      _checkWellKnownPath('$homeDirPath/android-studio');
    }
    return studios;
  }

271 272 273 274 275 276 277
  static String extractStudioPlistValueWithMatcher(String plistValue, RegExp keyMatcher) {
    if (plistValue == null || keyMatcher == null) {
      return null;
    }
    return keyMatcher?.stringMatch(plistValue)?.split('=')?.last?.trim()?.replaceAll('"', '');
  }

278 279 280 281 282 283 284 285 286 287 288 289 290
  void _init() {
    _isValid = false;
    _validationMessages.clear();

    if (configured != null) {
      _validationMessages.add('android-studio-dir = $configured');
    }

    if (!fs.isDirectorySync(directory)) {
      _validationMessages.add('Android Studio not found at $directory');
      return;
    }

291 292 293
    final String javaPath = platform.isMacOS ?
        fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home') :
        fs.path.join(directory, 'jre');
294 295
    final String javaExecutable = fs.path.join(javaPath, 'bin', 'java');
    if (!processManager.canRun(javaExecutable)) {
296
      _validationMessages.add('Unable to find bundled Java version.');
297 298 299 300 301
    } else {
      final ProcessResult result = processManager.runSync(<String>[javaExecutable, '-version']);
      if (result.exitCode == 0) {
        final List<String> versionLines = result.stderr.split('\n');
        final String javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
302
        _validationMessages.add('Java version $javaVersion');
303
        _javaPath = javaPath;
304
        _isValid = true;
305 306 307
      } else {
        _validationMessages.add('Unable to determine bundled Java version.');
      }
308
    }
309 310 311
  }

  @override
312
  String toString() => 'Android Studio ($version)';
313
}