doctor.dart 16 KB
Newer Older
1 2 3 4
// 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.

5
import 'dart:async';
6
import 'dart:convert' show UTF8;
Devon Carew's avatar
Devon Carew committed
7

8
import 'package:archive/archive.dart';
9

10
import 'android/android_studio_validator.dart';
11
import 'android/android_workflow.dart';
12
import 'artifacts.dart';
13
import 'base/common.dart';
14
import 'base/context.dart';
15
import 'base/file_system.dart';
16
import 'base/os.dart';
17
import 'base/platform.dart';
18
import 'base/process_manager.dart';
19
import 'cache.dart';
20
import 'device.dart';
21
import 'globals.dart';
22
import 'ios/ios_workflow.dart';
23
import 'ios/plist_utils.dart';
24
import 'version.dart';
Devon Carew's avatar
Devon Carew committed
25

26 27
Doctor get doctor => context[Doctor];

28 29 30
class Doctor {
  Doctor() {
    _androidWorkflow = new AndroidWorkflow();
31
    _iosWorkflow = new IOSWorkflow();
32 33 34 35 36 37 38 39 40
  }

  IOSWorkflow _iosWorkflow;
  AndroidWorkflow _androidWorkflow;

  IOSWorkflow get iosWorkflow => _iosWorkflow;

  AndroidWorkflow get androidWorkflow => _androidWorkflow;

41 42 43 44 45 46
  List<DoctorValidator> _validators;

  List<DoctorValidator> get validators {
    if (_validators == null) {
      _validators = <DoctorValidator>[];
      _validators.add(new _FlutterValidator());
47
      _validators.add(new _HostExecutableValidator());
48 49 50 51 52 53 54

      if (_androidWorkflow.appliesToHostPlatform)
        _validators.add(_androidWorkflow);

      if (_iosWorkflow.appliesToHostPlatform)
        _validators.add(_iosWorkflow);

55
      final List<DoctorValidator> ideValidators = <DoctorValidator>[];
56 57 58 59 60 61 62 63 64 65 66
      ideValidators.addAll(AndroidStudioValidator.allValidators);
      ideValidators.addAll(IntelliJValidator.installedValidators);
      if (ideValidators.isNotEmpty)
        _validators.addAll(ideValidators);
      else
        _validators.add(new NoIdeValidator());

      _validators.add(new DeviceValidator());
    }
    return _validators;
  }
67

68
  List<Workflow> get workflows {
69
    return new List<Workflow>.from(validators.where((DoctorValidator validator) => validator is Workflow));
70
  }
71

72
  /// Print a summary of the state of the tooling, as well as how to get more info.
73 74 75
  Future<Null> summary() async {
    printStatus(await summaryText);
  }
76

77
  Future<String> get summaryText async {
78
    final StringBuffer buffer = new StringBuffer();
79 80 81

    bool allGood = true;

82
    for (DoctorValidator validator in validators) {
83
      final ValidationResult result = await validator.validate();
84
      buffer.write('${result.leadingBox} ${validator.title} is ');
85
      if (result.type == ValidationType.missing)
86
        buffer.write('not installed.');
87
      else if (result.type == ValidationType.partial)
88
        buffer.write('partially installed; more components are available.');
89
      else
90 91 92 93 94 95 96
        buffer.write('fully installed.');

      if (result.statusInfo != null)
        buffer.write(' (${result.statusInfo})');

      buffer.writeln();

97 98 99 100 101 102
      if (result.type != ValidationType.installed)
        allGood = false;
    }

    if (!allGood) {
      buffer.writeln();
Devon Carew's avatar
Devon Carew committed
103
      buffer.writeln('Run "flutter doctor" for information about installing additional components.');
104 105 106 107 108
    }

    return buffer.toString();
  }

109
  /// Print verbose information about the state of installed tooling.
110
  Future<bool> diagnose() async {
111
    bool doctorResult = true;
112

113
    for (DoctorValidator validator in validators) {
114
      final ValidationResult result = await validator.validate();
115

116 117 118
      if (result.type == ValidationType.missing)
        doctorResult = false;

119 120 121 122 123 124
      if (result.statusInfo != null)
        printStatus('${result.leadingBox} ${validator.title} (${result.statusInfo})');
      else
        printStatus('${result.leadingBox} ${validator.title}');

      for (ValidationMessage message in result.messages) {
125
        final String text = message.message.replaceAll('\n', '\n      ');
126
        if (message.isError) {
127
          printStatus('    ✗ $text', emphasis: true);
128
        } else {
129
          printStatus('    • $text');
130 131
        }
      }
132 133

      printStatus('');
134
    }
135 136

    return doctorResult;
137 138 139 140 141 142 143
  }

  bool get canListAnything => workflows.any((Workflow workflow) => workflow.canListDevices);

  bool get canLaunchAnything => workflows.any((Workflow workflow) => workflow.canLaunchDevices);
}

Devon Carew's avatar
Devon Carew committed
144
/// A series of tools and required install steps for a target platform (iOS or Android).
145
abstract class Workflow {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  /// Whether the workflow applies to this platform (as in, should we ever try and use it).
  bool get appliesToHostPlatform;

  /// Are we functional enough to list devices?
  bool get canListDevices;

  /// Could this thing launch *something*? It may still have minor issues.
  bool get canLaunchDevices;
}

enum ValidationType {
  missing,
  partial,
  installed
}

162 163
abstract class DoctorValidator {
  DoctorValidator(this.title);
164

165
  final String title;
166

167
  Future<ValidationResult> validate();
168 169 170
}

class ValidationResult {
171
  ValidationResult(this.type, this.messages, { this.statusInfo });
172 173

  final ValidationType type;
174 175 176
  // A short message about the status.
  final String statusInfo;
  final List<ValidationMessage> messages;
177

178 179
  String get leadingBox {
    if (type == ValidationType.missing)
180
      return '[✗]';
181
    else if (type == ValidationType.installed)
182
      return '[✓]';
183 184 185
    else
      return '[-]';
  }
186
}
187

188 189 190
class ValidationMessage {
  ValidationMessage(this.message) : isError = false;
  ValidationMessage.error(this.message) : isError = true;
191

192 193
  final bool isError;
  final String message;
194

195 196 197
  @override
  String toString() => message;
}
198

199 200
class _FlutterValidator extends DoctorValidator {
  _FlutterValidator() : super('Flutter');
201

202
  @override
203
  Future<ValidationResult> validate() async {
204 205
    final List<ValidationMessage> messages = <ValidationMessage>[];
    final ValidationType valid = ValidationType.installed;
206

207
    final FlutterVersion version = FlutterVersion.instance;
208

209
    messages.add(new ValidationMessage('Flutter at ${Cache.flutterRoot}'));
210 211
    messages.add(new ValidationMessage(
      'Framework revision ${version.frameworkRevisionShort} '
212
      '(${version.frameworkAge}), ${version.frameworkDate}'
213
    ));
214 215
    messages.add(new ValidationMessage('Engine revision ${version.engineRevisionShort}'));
    messages.add(new ValidationMessage('Tools Dart version ${version.dartSdkVersion}'));
216

217
    return new ValidationResult(valid, messages,
218
      statusInfo: 'on ${os.name}, channel ${version.channel}');
219
  }
220
}
Devon Carew's avatar
Devon Carew committed
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
class _HostExecutableValidator extends DoctorValidator {
  _HostExecutableValidator() : super('Host Executable Compatibility');

  bool _genSnapshotRuns(String genSnapshotPath) {
    final int kExpectedExitCode = 255;
    try {
      return processManager.runSync(<String>[genSnapshotPath]).exitCode == kExpectedExitCode;
    } catch (error) {
      return false;
    }
  }

  @override
  Future<ValidationResult> validate() async {
    final String genSnapshotPath =
      artifacts.getArtifactPath(Artifact.genSnapshot);
    final List<ValidationMessage> messages = <ValidationMessage>[];
    final bool hostExecutablesRun = _genSnapshotRuns(genSnapshotPath);
    final ValidationType valid = hostExecutablesRun ? ValidationType.installed : ValidationType.missing;

    if (hostExecutablesRun) {
      messages.add(new ValidationMessage('Downloaded executables execute on host'));
    } else {
      messages.add(new ValidationMessage.error(
        'Downloaded executables cannot execute on host. See https://github.com/flutter/flutter/issues/6207 for more information'));
    }
    return new ValidationResult(valid, messages);
  }
}

252 253 254 255 256 257 258 259 260 261 262
class NoIdeValidator extends DoctorValidator {
  NoIdeValidator() : super('Flutter IDE Support');

  @override
  Future<ValidationResult> validate() async {
    return new ValidationResult(ValidationType.missing, <ValidationMessage>[
      new ValidationMessage('IntelliJ - https://www.jetbrains.com/idea/'),
    ], statusInfo: 'No supported IDEs installed');
  }
}

263 264
abstract class IntelliJValidator extends DoctorValidator {
  IntelliJValidator(String title) : super(title);
265

266 267
  String get version;
  String get pluginsPath;
268

269 270 271
  static final Map<String, String> _idToTitle = <String, String>{
    'IntelliJIdea' : 'IntelliJ IDEA Ultimate Edition',
    'IdeaIC' : 'IntelliJ IDEA Community Edition',
272
    'WebStorm': 'WebStorm',
273
  };
274

275
  static Iterable<DoctorValidator> get installedValidators {
276
    if (platform.isLinux || platform.isWindows)
277
      return IntelliJValidatorOnLinuxAndWindows.installed;
278
    if (platform.isMacOS)
279 280
      return IntelliJValidatorOnMac.installed;
    return <DoctorValidator>[];
281 282 283 284
  }

  @override
  Future<ValidationResult> validate() async {
285
    final List<ValidationMessage> messages = <ValidationMessage>[];
286 287 288

    int installCount = 0;

289 290
    if (isWebStorm) {
      // Dart is bundled with WebStorm.
291
      installCount++;
292 293 294 295
    } else {
      if (_validateHasPackage(messages, 'Dart', 'Dart'))
        installCount++;
    }
296

297
    if (_validateHasPackage(messages, 'flutter-intellij.jar', 'Flutter'))
298 299 300 301 302
      installCount++;

    if (installCount < 2) {
      messages.add(new ValidationMessage(
          'For information about managing plugins, see\n'
303
          'https://www.jetbrains.com/help/idea/managing-plugins.html'
304 305 306 307 308 309 310 311 312 313
      ));
    }

    return new ValidationResult(
        installCount == 2 ? ValidationType.installed : ValidationType.partial,
        messages,
        statusInfo: 'version $version'
    );
  }

314 315
  bool get isWebStorm => title == 'WebStorm';

316
  bool _validateHasPackage(List<ValidationMessage> messages, String packageName, String title) {
317 318
    if (!hasPackage(packageName)) {
      messages.add(new ValidationMessage(
319
        '$title plugin not installed; this adds $title specific functionality.'
320 321 322
      ));
      return false;
    }
323
    final String version = _readPackageVersion(packageName);
324 325
    messages.add(new ValidationMessage('$title plugin '
        '${version != null ? "version $version" : "installed"}'));
326 327 328
    return true;
  }

329
  String _readPackageVersion(String packageName) {
330
    final String jarPath = packageName.endsWith('.jar')
331 332
        ? fs.path.join(pluginsPath, packageName)
        : fs.path.join(pluginsPath, packageName, 'lib', '$packageName.jar');
333 334 335
    // TODO(danrubel) look for a better way to extract a single 2K file from the zip
    // rather than reading the entire file into memory.
    try {
336 337 338 339 340 341
      final Archive archive = new ZipDecoder().decodeBytes(fs.file(jarPath).readAsBytesSync());
      final ArchiveFile file = archive.findFile('META-INF/plugin.xml');
      final String content = UTF8.decode(file.content);
      final String versionStartTag = '<version>';
      final int start = content.indexOf(versionStartTag);
      final int end = content.indexOf('</version>', start);
342 343 344 345 346 347
      return content.substring(start + versionStartTag.length, end);
    } catch (_) {
      return null;
    }
  }

348
  bool hasPackage(String packageName) {
349
    final String packagePath = fs.path.join(pluginsPath, packageName);
350
    if (packageName.endsWith('.jar'))
351 352
      return fs.isFileSync(packagePath);
    return fs.isDirectorySync(packagePath);
353 354 355
  }
}

356 357
class IntelliJValidatorOnLinuxAndWindows extends IntelliJValidator {
  IntelliJValidatorOnLinuxAndWindows(String title, this.version, this.installPath, this.pluginsPath) : super(title);
358 359 360 361

  @override
  String version;

362 363
  final String installPath;

364 365 366 367
  @override
  String pluginsPath;

  static Iterable<DoctorValidator> get installed {
368
    final List<DoctorValidator> validators = <DoctorValidator>[];
369 370
    if (homeDirPath == null)
      return validators;
371 372

    void addValidator(String title, String version, String installPath, String pluginsPath) {
373
      final IntelliJValidatorOnLinuxAndWindows validator =
374
        new IntelliJValidatorOnLinuxAndWindows(title, version, installPath, pluginsPath);
375
      for (int index = 0; index < validators.length; ++index) {
376
        final DoctorValidator other = validators[index];
377
        if (other is IntelliJValidatorOnLinuxAndWindows && validator.installPath == other.installPath) {
378 379 380 381 382 383 384 385
          if (validator.version.compareTo(other.version) > 0)
            validators[index] = validator;
          return;
        }
      }
      validators.add(validator);
    }

386
    for (FileSystemEntity dir in fs.directory(homeDirPath).listSync()) {
387
      if (dir is Directory) {
388
        final String name = fs.path.basename(dir.path);
389 390
        IntelliJValidator._idToTitle.forEach((String id, String title) {
          if (name.startsWith('.$id')) {
391
            final String version = name.substring(id.length + 1);
392 393
            String installPath;
            try {
394
              installPath = fs.file(fs.path.join(dir.path, 'system', '.home')).readAsStringSync();
395 396 397
            } catch (e) {
              // ignored
            }
398
            if (installPath != null && fs.isDirectorySync(installPath)) {
399
              final String pluginsPath = fs.path.join(dir.path, 'config', 'plugins');
400
              addValidator(title, version, installPath, pluginsPath);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
            }
          }
        });
      }
    }
    return validators;
  }
}

class IntelliJValidatorOnMac extends IntelliJValidator {
  IntelliJValidatorOnMac(String title, this.id, this.installPath) : super(title);

  final String id;
  final String installPath;

  static final Map<String, String> _dirNameToId = <String, String>{
    'IntelliJ IDEA.app' : 'IntelliJIdea',
418
    'IntelliJ IDEA Ultimate.app' : 'IntelliJIdea',
419
    'IntelliJ IDEA CE.app' : 'IdeaIC',
420
    'WebStorm.app': 'WebStorm',
421 422 423
  };

  static Iterable<DoctorValidator> get installed {
424 425
    final List<DoctorValidator> validators = <DoctorValidator>[];
    final List<String> installPaths = <String>['/Applications', fs.path.join(homeDirPath, 'Applications')];
426 427

    void checkForIntelliJ(Directory dir) {
428
      final String name = fs.path.basename(dir.path);
429 430
      _dirNameToId.forEach((String dirName, String id) {
        if (name == dirName) {
431
          final String title = IntelliJValidator._idToTitle[id];
432 433 434 435 436
          validators.add(new IntelliJValidatorOnMac(title, id, dir.path));
        }
      });
    }

437
    try {
438
      final Iterable<FileSystemEntity> installDirs = installPaths
439 440 441 442
              .map((String installPath) => fs.directory(installPath).listSync())
              .expand((List<FileSystemEntity> mappedDirs) => mappedDirs)
              .where((FileSystemEntity mappedDir) => mappedDir is Directory);
      for (FileSystemEntity dir in installDirs) {
443 444 445 446
        if (dir is Directory) {
          checkForIntelliJ(dir);
          if (!dir.path.endsWith('.app')) {
            for (FileSystemEntity subdir in dir.listSync()) {
447
              if (subdir is Directory) {
448
                checkForIntelliJ(subdir);
449
              }
450
            }
451
          }
452
        }
453
      }
454 455 456 457 458 459 460
    } on FileSystemException catch (e) {
      validators.add(new ValidatorWithResult(
          'Cannot determine if IntelliJ is installed',
          new ValidationResult(ValidationType.missing, <ValidationMessage>[
             new ValidationMessage.error(e.message),
          ]),
      ));
461 462 463 464 465 466 467
    }
    return validators;
  }

  @override
  String get version {
    if (_version == null) {
468
      final String plistFile = fs.path.join(installPath, 'Contents', 'Info.plist');
469
      _version = getValueFromFile(plistFile, kCFBundleShortVersionStringKey) ?? 'unknown';
470 471 472 473 474 475 476
    }
    return _version;
  }
  String _version;

  @override
  String get pluginsPath {
477 478 479
    final List<String> split = version.split('.');
    final String major = split[0];
    final String minor = split[1];
480
    return fs.path.join(homeDirPath, 'Library', 'Application Support', '$id$major.$minor');
481 482 483
  }
}

484 485 486 487 488
class DeviceValidator extends DoctorValidator {
  DeviceValidator() : super('Connected devices');

  @override
  Future<ValidationResult> validate() async {
489
    final List<Device> devices = await deviceManager.getAllConnectedDevices().toList();
490 491 492 493
    List<ValidationMessage> messages;
    if (devices.isEmpty) {
      messages = <ValidationMessage>[new ValidationMessage('None')];
    } else {
494
      messages = await Device.descriptions(devices)
495 496 497 498 499
          .map((String msg) => new ValidationMessage(msg)).toList();
    }
    return new ValidationResult(ValidationType.installed, messages);
  }
}
500 501 502 503 504 505 506 507 508

class ValidatorWithResult extends DoctorValidator {
  final ValidationResult result;

  ValidatorWithResult(String title, this.result) : super(title);

  @override
  Future<ValidationResult> validate() async => result;
}