analyze.dart 30.5 KB
Newer Older
Hixie's avatar
Hixie committed
1 2 3 4 5
// Copyright 2015 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 'dart:async';
6
import 'dart:collection';
Hixie's avatar
Hixie committed
7 8 9
import 'dart:convert';
import 'dart:io';

10
import 'package:den_api/den_api.dart';
Hixie's avatar
Hixie committed
11 12 13
import 'package:path/path.dart' as path;

import '../artifacts.dart';
14
import '../base/process.dart';
15
import '../base/utils.dart';
16
import '../build_configuration.dart';
17
import '../dart/sdk.dart';
18
import '../globals.dart';
19
import '../runner/flutter_command.dart';
Hixie's avatar
Hixie committed
20

21 22 23 24
bool isDartFile(FileSystemEntity entry) => entry is File && entry.path.endsWith('.dart');
bool isDartTestFile(FileSystemEntity entry) => entry is File && entry.path.endsWith('_test.dart');
bool isDartBenchmarkFile(FileSystemEntity entry) => entry is File && entry.path.endsWith('_bench.dart');

25
void _addPackage(String directoryPath, List<String> dartFiles, Set<String> pubSpecDirectories) {
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  final int originalDartFilesCount = dartFiles.length;

  // .../directoryPath/*/bin/*.dart
  // .../directoryPath/*/lib/main.dart
  // .../directoryPath/*/test/*_test.dart
  // .../directoryPath/*/test/*/*_test.dart
  // .../directoryPath/*/benchmark/*/*_bench.dart

  Directory binDirectory = new Directory(path.join(directoryPath, 'bin'));
  if (binDirectory.existsSync()) {
    for (FileSystemEntity subentry in binDirectory.listSync()) {
      if (isDartFile(subentry))
        dartFiles.add(subentry.path);
    }
  }

  String mainPath = path.join(directoryPath, 'lib', 'main.dart');
  if (FileSystemEntity.isFileSync(mainPath))
    dartFiles.add(mainPath);

  Directory testDirectory = new Directory(path.join(directoryPath, 'test'));
  if (testDirectory.existsSync()) {
    for (FileSystemEntity entry in testDirectory.listSync()) {
      if (entry is Directory) {
        for (FileSystemEntity subentry in entry.listSync()) {
          if (isDartTestFile(subentry))
            dartFiles.add(subentry.path);
        }
      } else if (isDartTestFile(entry)) {
        dartFiles.add(entry.path);
      }
    }
  }

60 61 62 63 64 65 66 67 68 69 70 71 72 73
  Directory testDriverDirectory = new Directory(path.join(directoryPath, 'test_driver'));
  if (testDriverDirectory.existsSync()) {
    for (FileSystemEntity entry in testDriverDirectory.listSync()) {
      if (entry is Directory) {
        for (FileSystemEntity subentry in entry.listSync()) {
          if (isDartTestFile(subentry))
            dartFiles.add(subentry.path);
        }
      } else if (isDartTestFile(entry)) {
        dartFiles.add(entry.path);
      }
    }
  }

74 75 76 77 78 79 80 81 82 83 84 85 86 87
  Directory benchmarkDirectory = new Directory(path.join(directoryPath, 'benchmark'));
  if (benchmarkDirectory.existsSync()) {
    for (FileSystemEntity entry in benchmarkDirectory.listSync()) {
      if (entry is Directory) {
        for (FileSystemEntity subentry in entry.listSync()) {
          if (isDartBenchmarkFile(subentry))
            dartFiles.add(subentry.path);
        }
      } else if (isDartBenchmarkFile(entry)) {
        dartFiles.add(entry.path);
      }
    }
  }

88
  if (originalDartFilesCount != dartFiles.length)
89 90 91
    pubSpecDirectories.add(directoryPath);
}

92 93 94 95 96 97 98 99 100 101 102 103
/// Adds all packages in [subPath], assuming a flat directory structure, i.e.
/// each direct child of [subPath] is a plain Dart package.
void _addFlatPackageList(String subPath, List<String> dartFiles, Set<String> pubSpecDirectories) {
  Directory subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, subPath));
  if (subdirectory.existsSync()) {
    for (FileSystemEntity entry in subdirectory.listSync()) {
      if (entry is Directory)
        _addPackage(entry.path, dartFiles, pubSpecDirectories);
    }
  }
}

104 105
class FileChanged { }

Hixie's avatar
Hixie committed
106 107 108 109 110
class AnalyzeCommand extends FlutterCommand {
  AnalyzeCommand() {
    argParser.addFlag('flutter-repo', help: 'Include all the examples and tests from the Flutter repository.', defaultsTo: false);
    argParser.addFlag('current-directory', help: 'Include all the Dart files in the current directory, if any.', defaultsTo: true);
    argParser.addFlag('current-package', help: 'Include the lib/main.dart file from the current directory, if any.', defaultsTo: true);
111
    argParser.addFlag('preamble', help: 'Display the number of files that will be analyzed.', defaultsTo: true);
Hixie's avatar
Hixie committed
112
    argParser.addFlag('congratulate', help: 'Show output even when there are no errors, warnings, hints, or lints.', defaultsTo: true);
113
    argParser.addFlag('watch', help: 'Run analysis continuously, watching the filesystem for changes.', negatable: false);
Hixie's avatar
Hixie committed
114 115
  }

116
  @override
Ian Hickson's avatar
Ian Hickson committed
117
  String get name => 'analyze';
118 119

  @override
Ian Hickson's avatar
Ian Hickson committed
120
  String get description => 'Analyze the project\'s Dart code.';
121 122

  @override
Hixie's avatar
Hixie committed
123 124
  bool get requiresProjectRoot => false;

125 126 127 128 129 130
  bool get isFlutterRepo {
    return FileSystemEntity.isDirectorySync('examples') &&
      FileSystemEntity.isDirectorySync('packages') &&
      FileSystemEntity.isFileSync('bin/flutter');
  }

Hixie's avatar
Hixie committed
131 132
  @override
  Future<int> runInProject() async {
133 134 135
    return argResults['watch'] ? _analyzeWatch() : _analyzeOnce();
  }

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  List<String> flutterRootComponents;
  bool isFlutterLibrary(String filename) {
    flutterRootComponents ??= path.normalize(path.absolute(ArtifactStore.flutterRoot)).split(path.separator);
    List<String> filenameComponents = path.normalize(path.absolute(filename)).split(path.separator);
    if (filenameComponents.length < flutterRootComponents.length + 4) // the 4: 'packages', package_name, 'lib', file_name
      return false;
    for (int index = 0; index < flutterRootComponents.length; index += 1) {
      if (flutterRootComponents[index] != filenameComponents[index])
        return false;
    }
    if (filenameComponents[flutterRootComponents.length] != 'packages')
      return false;
    if (filenameComponents[flutterRootComponents.length + 1] == 'flutter_tools')
      return false;
    if (filenameComponents[flutterRootComponents.length + 2] != 'lib')
      return false;
    return true;
  }

155
  Future<int> _analyzeOnce() async {
156
    Stopwatch stopwatch = new Stopwatch()..start();
157
    Set<String> pubSpecDirectories = new HashSet<String>();
Hixie's avatar
Hixie committed
158 159 160
    List<String> dartFiles = argResults.rest.toList();

    for (String file in dartFiles) {
161 162 163 164 165 166 167 168 169
      file = path.normalize(path.absolute(file));
      String root = path.rootPrefix(file);
      while (file != root) {
        file = path.dirname(file);
        if (FileSystemEntity.isFileSync(path.join(file, 'pubspec.yaml'))) {
          pubSpecDirectories.add(file);
          break;
        }
      }
Hixie's avatar
Hixie committed
170 171 172 173 174 175 176
    }

    if (argResults['current-directory']) {
      // ./*.dart
      Directory currentDirectory = new Directory('.');
      bool foundOne = false;
      for (FileSystemEntity entry in currentDirectory.listSync()) {
177
        if (isDartFile(entry)) {
Hixie's avatar
Hixie committed
178 179 180 181
          dartFiles.add(entry.path);
          foundOne = true;
        }
      }
182
      if (foundOne)
Hixie's avatar
Hixie committed
183 184 185
        pubSpecDirectories.add('.');
    }

186 187
    if (argResults['current-package'])
      _addPackage('.', dartFiles, pubSpecDirectories);
188 189 190 191 192 193 194

    if (argResults['flutter-repo']) {
      //examples/*/ as package
      //examples/layers/*/ as files
      //dev/manual_tests/*/ as package
      //dev/manual_tests/*/ as files

195 196
      _addFlatPackageList('packages', dartFiles, pubSpecDirectories);
      _addFlatPackageList('examples', dartFiles, pubSpecDirectories);
197

198
      Directory subdirectory;
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

      subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, 'examples', 'layers'));
      if (subdirectory.existsSync()) {
        bool foundOne = false;
        for (FileSystemEntity entry in subdirectory.listSync()) {
          if (entry is Directory) {
            for (FileSystemEntity subentry in entry.listSync()) {
              if (isDartFile(subentry)) {
                dartFiles.add(subentry.path);
                foundOne = true;
              }
            }
          }
        }
        if (foundOne)
          pubSpecDirectories.add(subdirectory.path);
      }

      subdirectory = new Directory(path.join(ArtifactStore.flutterRoot, 'dev', 'manual_tests'));
      if (subdirectory.existsSync()) {
        bool foundOne = false;
        for (FileSystemEntity entry in subdirectory.listSync()) {
          if (entry is Directory) {
            _addPackage(entry.path, dartFiles, pubSpecDirectories);
          } else if (isDartFile(entry)) {
            dartFiles.add(entry.path);
            foundOne = true;
          }
        }
        if (foundOne)
          pubSpecDirectories.add(subdirectory.path);
      }

Hixie's avatar
Hixie committed
232 233
    }

234
    dartFiles = dartFiles.map((String directory) => path.normalize(path.absolute(directory))).toSet().toList();
235 236
    dartFiles.sort();

Hixie's avatar
Hixie committed
237 238
    // prepare a Dart file that references all the above Dart files
    StringBuffer mainBody = new StringBuffer();
239
    for (int index = 0; index < dartFiles.length; index += 1)
240
      mainBody.writeln('import \'${dartFiles[index]}\' as file$index;');
Hixie's avatar
Hixie committed
241 242
    mainBody.writeln('void main() { }');

243 244
    // determine what all the various .packages files depend on
    PackageDependencyTracker dependencies = new PackageDependencyTracker();
Ian Hickson's avatar
Ian Hickson committed
245
    for (Directory directory in pubSpecDirectories.map((String path) => new Directory(path))) {
246 247 248
      String pubSpecYamlPath = path.join(directory.path, 'pubspec.yaml');
      File pubSpecYamlFile = new File(pubSpecYamlPath);
      if (pubSpecYamlFile.existsSync()) {
249 250 251
        // we are analyzing the actual canonical source for this package;
        // make sure we remember that, in case all the packages are actually
        // pointing elsewhere somehow.
252 253 254
        Pubspec pubSpecYaml = await Pubspec.load(pubSpecYamlPath);
        String packageName = pubSpecYaml.name;
        String packagePath = path.normalize(path.absolute(path.join(directory.path, 'lib')));
255
        dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath);
256
      }
257 258
      String dotPackagesPath = path.join(directory.path, '.packages');
      File dotPackages = new File(dotPackagesPath);
Hixie's avatar
Hixie committed
259
      if (dotPackages.existsSync()) {
260
        // this directory has opinions about what we should be using
Hixie's avatar
Hixie committed
261 262 263
        dotPackages
          .readAsStringSync()
          .split('\n')
Ian Hickson's avatar
Ian Hickson committed
264 265
          .where((String line) => !line.startsWith(new RegExp(r'^ *#')))
          .forEach((String line) {
Hixie's avatar
Hixie committed
266 267
            int colon = line.indexOf(':');
            if (colon > 0)
268
              dependencies.add(line.substring(0, colon), path.normalize(path.absolute(directory.path, path.fromUri(line.substring(colon+1)))), dotPackagesPath);
Hixie's avatar
Hixie committed
269 270 271
          });
      }
    }
272 273 274 275 276 277 278 279 280

    // prepare a union of all the .packages files
    if (dependencies.hasConflicts) {
      printError(dependencies.generateConflictReport());
      printError('Make sure you have run "pub upgrade" in all the directories mentioned above.');
      if (dependencies.hasConflictsAffectingFlutterRepo)
        printError('For packages in the flutter repository, try using "flutter update-packages --upgrade" to do all of them at once.');
      printError('If this does not help, to track down the conflict you can use "pub deps --style=list" and "pub upgrade --verbosity=solver" in the affected directories.');
      return 1;
Hixie's avatar
Hixie committed
281
    }
282
    Map<String, String> packages = dependencies.asPackageMap();
Hixie's avatar
Hixie committed
283

284
    // override the sky_engine and sky_services packages if the user is using a local build
Hixie's avatar
Hixie committed
285 286 287 288 289 290 291 292 293 294 295 296 297
    String buildDir = buildConfigurations.firstWhere((BuildConfiguration config) => config.testable, orElse: () => null)?.buildDir;
    if (buildDir != null) {
      packages['sky_engine'] = path.join(buildDir, 'gen/dart-pkg/sky_engine/lib');
      packages['sky_services'] = path.join(buildDir, 'gen/dart-pkg/sky_services/lib');
    }

    StringBuffer packagesBody = new StringBuffer();
    for (String package in packages.keys)
      packagesBody.writeln('$package:${path.toUri(packages[package])}');

    // save the Dart file and the .packages file to disk
    Directory host = Directory.systemTemp.createTempSync('flutter-analyze-');
    File mainFile = new File(path.join(host.path, 'main.dart'))..writeAsStringSync(mainBody.toString());
298
    File optionsFile = new File(path.join(ArtifactStore.flutterRoot, 'packages', 'flutter_tools', '.analysis_options'));
Hixie's avatar
Hixie committed
299 300 301 302 303 304
    File packagesFile = new File(path.join(host.path, '.packages'))..writeAsStringSync(packagesBody.toString());

    List<String> cmd = <String>[
      sdkBinaryName('dartanalyzer'),
      // do not set '--warnings', since that will include the entire Dart SDK
      '--ignore-unrecognized-flags',
305
      '--enable-strict-call-checks', //TODO(pq): migrate to options once supported (dart/sdk#25983)
Hixie's avatar
Hixie committed
306 307 308 309
      '--enable_type_checks',
      '--package-warnings',
      '--fatal-warnings',
      '--fatal-hints',
310 311
      // defines lints
      '--options', optionsFile.path,
Hixie's avatar
Hixie committed
312 313 314 315
      '--packages', packagesFile.path,
      mainFile.path
    ];

316 317 318 319
    if (argResults['preamble']) {
      if (dartFiles.length == 1) {
        printStatus('Analyzing ${dartFiles.first}...');
      } else {
320
        printStatus('Analyzing ${dartFiles.length} entry points...');
321
      }
322 323
      for (String file in dartFiles)
        printTrace(file);
324 325
    }

326
    printTrace(cmd.join(' '));
Hixie's avatar
Hixie committed
327 328 329 330 331 332 333 334 335 336 337 338 339
    Process process = await Process.start(
      cmd[0],
      cmd.sublist(1),
      workingDirectory: host.path
    );
    int errorCount = 0;
    StringBuffer output = new StringBuffer();
    process.stdout.transform(UTF8.decoder).listen((String data) {
      output.write(data);
    });
    process.stderr.transform(UTF8.decoder).listen((String data) {
      // dartanalyzer doesn't seem to ever output anything on stderr
      errorCount += 1;
340
      printError(data);
Hixie's avatar
Hixie committed
341 342 343 344 345 346
    });

    int exitCode = await process.exitCode;

    List<Pattern> patternsToSkip = <Pattern>[
      'Analyzing [${mainFile.path}]...',
347
      new RegExp('^\\[(hint|error)\\] Unused import \\(${mainFile.path},'),
Hixie's avatar
Hixie committed
348
      new RegExp(r'^\[.+\] .+ \(.+/\.pub-cache/.+'),
349
      new RegExp('\\[warning\\] Missing concrete implementation of \'RenderObject\\.applyPaintTransform\''), // https://github.com/dart-lang/sdk/issues/25232
350 351
      new RegExp(r'[0-9]+ (error|warning|hint|lint).+found\.'),
      new RegExp(r'^$'),
Hixie's avatar
Hixie committed
352 353 354
    ];

    RegExp generalPattern = new RegExp(r'^\[(error|warning|hint|lint)\] (.+) \(([^(),]+), line ([0-9]+), col ([0-9]+)\)$');
Ian Hickson's avatar
Ian Hickson committed
355
    RegExp allowedIdentifiersPattern = new RegExp(r'_?([A-Z]|_+)\b');
356
    RegExp classesWithOptionalTypeArgumentsPattern = new RegExp(r'\b(GlobalKey|State|ScrollableState|Element|StatelessElement|TypeMatcher)\b');
Hixie's avatar
Hixie committed
357
    RegExp constructorTearOffsPattern = new RegExp('.+#.+// analyzer doesn\'t like constructor tear-offs');
358
    RegExp conflictingNamesPattern = new RegExp('^The imported libraries \'([^\']+)\' and \'([^\']+)\' cannot have the same name \'([^\']+)\'\$');
359
    RegExp missingFilePattern = new RegExp('^Target of URI does not exist: \'([^\')]+)\'\$');
360
    RegExp documentAllMembersPattern = new RegExp('^Document all public memm?bers\$');
Hixie's avatar
Hixie committed
361

362 363
    Set<String> changedFiles = new Set<String>(); // files about which we've complained that they changed

Hixie's avatar
Hixie committed
364 365 366 367 368 369 370 371 372 373 374 375
    List<String> errorLines = output.toString().split('\n');
    for (String errorLine in errorLines) {
      if (patternsToSkip.every((Pattern pattern) => pattern.allMatches(errorLine).isEmpty)) {
        Match groups = generalPattern.firstMatch(errorLine);
        if (groups != null) {
          String level = groups[1];
          String filename = groups[3];
          String errorMessage = groups[2];
          int lineNumber = int.parse(groups[4]);
          int colNumber = int.parse(groups[5]);
          File source = new File(filename);
          List<String> sourceLines = source.readAsLinesSync();
376 377 378 379 380 381 382 383 384 385 386 387 388 389
          String sourceLine;
          try {
            if (lineNumber > sourceLines.length)
              throw new FileChanged();
            sourceLine = sourceLines[lineNumber-1];
            if (colNumber > sourceLine.length)
              throw new FileChanged();
          } on FileChanged {
            if (changedFiles.add(filename))
              printError('[warning] File shrank during analysis ($filename)');
            sourceLine = '';
            lineNumber = 1;
            colNumber = 1;
          }
Hixie's avatar
Hixie committed
390
          bool shouldIgnore = false;
391 392 393 394 395
          if (documentAllMembersPattern.firstMatch(errorMessage) != null) {
            // https://github.com/dart-lang/linter/issues/207
            // https://github.com/dart-lang/linter/issues/208
            shouldIgnore = !isFlutterLibrary(filename);
          } else if (filename == mainFile.path) {
396
            Match libs = conflictingNamesPattern.firstMatch(errorMessage);
397
            Match missing = missingFilePattern.firstMatch(errorMessage);
398 399
            if (libs != null) {
              errorLine = '[$level] $errorMessage (${dartFiles[lineNumber-1]})'; // strip the reference to the generated main.dart
400 401
            } else if (missing != null) {
              errorLine = '[$level] File does not exist (${missing[1]})';
402 403 404 405
            } else {
              errorLine += ' (Please file a bug on the "flutter analyze" command saying that you saw this message.)';
            }
          } else if (filename.endsWith('.mojom.dart')) {
Ian Hickson's avatar
Ian Hickson committed
406 407
            // autogenerated code - TODO(ianh): Fix the Dart mojom compiler
            shouldIgnore = true;
408
          } else if (sourceLines.first.startsWith('// DO NOT EDIT. This is code generated')) {
Ian Hickson's avatar
Ian Hickson committed
409
            // autogenerated code - TODO(ianh): Fix the intl package resource generator
Hixie's avatar
Hixie committed
410 411
            shouldIgnore = true;
          } else if (level == 'lint' && errorMessage == 'Name non-constant identifiers using lowerCamelCase.') {
Ian Hickson's avatar
Ian Hickson committed
412
            if (allowedIdentifiersPattern.matchAsPrefix(sourceLine, colNumber-1) != null)
Hixie's avatar
Hixie committed
413
              shouldIgnore = true;
414 415 416 417 418
          } else if (level == 'lint' && errorMessage == 'Specify type annotations.') {
            // we want the type annotations on certain classes to be optional.
            // see https://github.com/dart-lang/linter/issues/196
            if (classesWithOptionalTypeArgumentsPattern.matchAsPrefix(sourceLine, colNumber-1) != null)
              shouldIgnore = true;
Hixie's avatar
Hixie committed
419 420 421 422 423 424
          } else if (constructorTearOffsPattern.allMatches(sourceLine).isNotEmpty) {
            shouldIgnore = true;
          }
          if (shouldIgnore)
            continue;
        }
425
        printError(errorLine);
Hixie's avatar
Hixie committed
426 427 428
        errorCount += 1;
      }
    }
429
    stopwatch.stop();
430
    String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
Hixie's avatar
Hixie committed
431

432 433
    host.deleteSync(recursive: true);

434
    if (exitCode < 0 || exitCode > 3) // analyzer exit codes: 0 = nothing, 1 = hints, 2 = warnings, 3 = errors
Hixie's avatar
Hixie committed
435 436
      return exitCode;

437
    if (errorCount > 0)
438
      return 1; // we consider any level of error to be an error exit (we don't report different levels)
Hixie's avatar
Hixie committed
439
    if (argResults['congratulate'])
440
      printStatus('No analyzer warnings! (ran in ${elapsed}s)');
Hixie's avatar
Hixie committed
441 442
    return 0;
  }
443 444 445 446

  Future<int> _analyzeWatch() async {
    List<String> directories;

447 448 449
    if (argResults['flutter-repo']) {
      String root = path.absolute(ArtifactStore.flutterRoot);

450
      directories = <String>[];
451 452 453
      directories.addAll(_gatherProjectPaths(path.join(root, 'examples')));
      directories.addAll(_gatherProjectPaths(path.join(root, 'packages')));
      directories.addAll(_gatherProjectPaths(path.join(root, 'dev')));
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
      printStatus('Analyzing Flutter repository (${directories.length} projects).');
      for (String projectPath in directories)
        printTrace('  ${path.relative(projectPath)}');
      printStatus('');
    } else {
      directories = <String>[Directory.current.path];
    }

    AnalysisServer server = new AnalysisServer(dartSdkPath, directories);
    server.onAnalyzing.listen(_handleAnalysisStatus);
    server.onErrors.listen(_handleAnalysisErrors);

    await server.start();

    int exitCode = await server.onExit;
    printStatus('Analysis server exited with code $exitCode.');
    return 0;
  }

  bool firstAnalysis = true;
  Set<String> analyzedPaths = new Set<String>();
  Map<String, List<AnalysisError>> analysisErrors = <String, List<AnalysisError>>{};
  Stopwatch analysisTimer;
  int lastErrorCount = 0;

  void _handleAnalysisStatus(bool isAnalyzing) {
    if (isAnalyzing) {
      if (firstAnalysis) {
        printStatus('Analyzing ${path.basename(Directory.current.path)}...');
      } else {
        printStatus('');
      }

      analyzedPaths.clear();
      analysisTimer = new Stopwatch()..start();
    } else {
      analysisTimer.stop();

      // Sort and print errors.
      List<AnalysisError> errors = <AnalysisError>[];
      for (List<AnalysisError> fileErrors in analysisErrors.values)
        errors.addAll(fileErrors);

      errors.sort();

499
      for (AnalysisError error in errors) {
500
        printStatus(error.toString());
501 502 503
        if (error.code != null)
          printTrace('error code: ${error.code}');
      }
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558

      // Print an analysis summary.
      String errorsMessage;

      int issueCount = errors.length;
      int issueDiff = issueCount - lastErrorCount;
      lastErrorCount = issueCount;

      if (firstAnalysis)
        errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found';
      else if (issueDiff > 0)
        errorsMessage = '$issueDiff new ${pluralize('issue', issueDiff)}, $issueCount total';
      else if (issueDiff < 0)
        errorsMessage = '${-issueDiff} ${pluralize('issue', -issueDiff)} fixed, $issueCount remaining';
      else if (issueCount != 0)
        errorsMessage = 'no new issues, $issueCount total';
      else
        errorsMessage = 'no issues found';

      String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}';
      String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2);
      printStatus('$errorsMessage • analyzed $files, $seconds seconds');

      firstAnalysis = false;
    }
  }

  void _handleAnalysisErrors(FileAnalysisErrors fileErrors) {
    fileErrors.errors.removeWhere(_filterError);

    analyzedPaths.add(fileErrors.file);
    analysisErrors[fileErrors.file] = fileErrors.errors;
  }

  bool _filterError(AnalysisError error) {
    // TODO(devoncarew): Also filter the regex items from `analyzeOnce()`.

    if (error.type == 'TODO')
      return true;

    return false;
  }

  List<String> _gatherProjectPaths(String rootPath) {
    if (FileSystemEntity.isFileSync(path.join(rootPath, 'pubspec.yaml')))
      return <String>[rootPath];

    return new Directory(rootPath)
      .listSync(followLinks: false)
      .expand((FileSystemEntity entity) {
        return entity is Directory ? _gatherProjectPaths(entity.path) : <String>[];
      });
  }
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 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
class PackageDependency {
  // This is a map from dependency targets (lib directories) to a list
  // of places that ask for that target (.packages or pubspec.yaml files)
  Map<String, List<String>> values = <String, List<String>>{};
  String canonicalSource;
  void addCanonicalCase(String packagePath, String pubSpecYamlPath) {
    assert(canonicalSource == null);
    add(packagePath, pubSpecYamlPath);
    canonicalSource = pubSpecYamlPath;
  }
  void add(String packagePath, String sourcePath) {
    values.putIfAbsent(packagePath, () => <String>[]).add(sourcePath);
  }
  bool get hasConflict => values.length > 1;
  bool get hasConflictAffectingFlutterRepo {
    assert(path.isAbsolute(ArtifactStore.flutterRoot));
    for (List<String> targetSources in values.values) {
      for (String source in targetSources) {
        assert(path.isAbsolute(source));
        if (path.isWithin(ArtifactStore.flutterRoot, source))
          return true;
      }
    }
    return false;
  }
  void describeConflict(StringBuffer result) {
    assert(hasConflict);
    List<String> targets = values.keys.toList();
    targets.sort((String a, String b) => values[b].length.compareTo(values[a].length));
    for (String target in targets) {
      int count = values[target].length;
      result.writeln('  $count ${count == 1 ? 'source wants' : 'sources want'} "$target":');
      bool canonical = false;
      for (String source in values[target]) {
        result.writeln('    $source');
        if (source == canonicalSource)
          canonical = true;
      }
      if (canonical) {
        result.writeln('    (This is the actual package definition, so it is considered the canonical "right answer".)');
      }
    }
  }
  String get target => values.keys.single;
}

class PackageDependencyTracker {
  // This is a map from package names to objects that track the paths
  // involved (sources and targets).
  Map<String, PackageDependency> packages = <String, PackageDependency>{};

  PackageDependency getPackageDependency(String packageName) {
    return packages.putIfAbsent(packageName, () => new PackageDependency());
  }

  void addCanonicalCase(String packageName, String packagePath, String pubSpecYamlPath) {
    getPackageDependency(packageName).addCanonicalCase(packagePath, pubSpecYamlPath);
  }

  void add(String packageName, String packagePath, String dotPackagesPath) {
    getPackageDependency(packageName).add(packagePath, dotPackagesPath);
  }

  bool get hasConflicts {
    return packages.values.any((PackageDependency dependency) => dependency.hasConflict);
  }

  bool get hasConflictsAffectingFlutterRepo {
    return packages.values.any((PackageDependency dependency) => dependency.hasConflictAffectingFlutterRepo);
  }

  String generateConflictReport() {
    assert(hasConflicts);
    StringBuffer result = new StringBuffer();
    for (String package in packages.keys.where((String package) => packages[package].hasConflict)) {
      result.writeln('Package "$package" has conflicts:');
      packages[package].describeConflict(result);
    }
637
    return result.toString();
638 639 640 641 642 643 644 645 646 647
  }

  Map<String, String> asPackageMap() {
    Map<String, String> result = <String, String>{};
    for (String package in packages.keys)
      result[package] = packages[package].target;
    return result;
  }
}

648 649 650 651 652 653 654 655 656 657 658 659
class AnalysisServer {
  AnalysisServer(this.sdk, this.directories);

  final String sdk;
  final List<String> directories;

  Process _process;
  StreamController<bool> _analyzingController = new StreamController<bool>.broadcast();
  StreamController<FileAnalysisErrors> _errorsController = new StreamController<FileAnalysisErrors>.broadcast();

  int _id = 0;

Ian Hickson's avatar
Ian Hickson committed
660
  Future<Null> start() async {
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    String snapshot = path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot');
    List<String> args = <String>[snapshot, '--sdk', sdk];

    printTrace('dart ${args.join(' ')}');
    _process = await Process.start('dart', args);
    _process.exitCode.whenComplete(() => _process = null);

    Stream<String> errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter());
    errorStream.listen((String error) => printError(error));

    Stream<String> inStream = _process.stdout.transform(UTF8.decoder).transform(const LineSplitter());
    inStream.listen(_handleServerResponse);

    // Available options (many of these are obsolete):
    //   enableAsync, enableDeferredLoading, enableEnums, enableNullAwareOperators,
    //   enableSuperMixins, generateDart2jsHints, generateHints, generateLints
    _sendCommand('analysis.updateOptions', <String, dynamic>{
      'options': <String, dynamic>{
        'enableSuperMixins': true
      }
    });

    _sendCommand('server.setSubscriptions', <String, dynamic>{
      'subscriptions': <String>['STATUS']
    });

    _sendCommand('analysis.setAnalysisRoots', <String, dynamic>{
      'included': directories,
      'excluded': <String>[]
    });
  }

  Stream<bool> get onAnalyzing => _analyzingController.stream;
  Stream<FileAnalysisErrors> get onErrors => _errorsController.stream;

  Future<int> get onExit => _process.exitCode;

  void _sendCommand(String method, Map<String, dynamic> params) {
    String message = JSON.encode(<String, dynamic> {
      'id': (++_id).toString(),
      'method': method,
      'params': params
    });
    _process.stdin.writeln(message);
    printTrace('==> $message');
  }

  void _handleServerResponse(String line) {
    printTrace('<== $line');

    dynamic response = JSON.decode(line);

Ian Hickson's avatar
Ian Hickson committed
713
    if (response is Map<dynamic, dynamic>) {
714 715 716 717
      if (response['event'] != null) {
        String event = response['event'];
        dynamic params = response['params'];

Ian Hickson's avatar
Ian Hickson committed
718
        if (params is Map<dynamic, dynamic>) {
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
          if (event == 'server.status')
            _handleStatus(response['params']);
          else if (event == 'analysis.errors')
            _handleAnalysisIssues(response['params']);
          else if (event == 'server.error')
            _handleServerError(response['params']);
        }
      } else if (response['error'] != null) {
        printError('Error from the analysis server: ${response['error']['message']}');
      }
    }
  }

  void _handleStatus(Map<String, dynamic> statusInfo) {
    // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}}
    if (statusInfo['analysis'] != null) {
      bool isAnalyzing = statusInfo['analysis']['isAnalyzing'];
      _analyzingController.add(isAnalyzing);
    }
  }

  void _handleServerError(Map<String, dynamic> errorInfo) {
    printError('Error from the analysis server: ${errorInfo['message']}');
  }

  void _handleAnalysisIssues(Map<String, dynamic> issueInfo) {
    // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
    String file = issueInfo['file'];
    List<AnalysisError> errors = issueInfo['errors'].map((Map<String, dynamic> json) => new AnalysisError(json)).toList();
    _errorsController.add(new FileAnalysisErrors(file, errors));
  }

Ian Hickson's avatar
Ian Hickson committed
751
  Future<bool> dispose() async => _process?.kill();
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
}

class FileAnalysisErrors {
  FileAnalysisErrors(this.file, this.errors);

  final String file;
  final List<AnalysisError> errors;
}

class AnalysisError implements Comparable<AnalysisError> {
  AnalysisError(this.json);

  static final Map<String, int> _severityMap = <String, int> {
    'ERROR': 3,
    'WARNING': 2,
    'INFO': 1
  };

  // "severity":"INFO","type":"TODO","location":{
  //   "file":"/Users/.../lib/test.dart","offset":362,"length":72,"startLine":15,"startColumn":4
  // },"message":"...","hasFix":false}
  Map<String, dynamic> json;

  String get severity => json['severity'];
  int get severityLevel => _severityMap[severity] ?? 0;
  String get type => json['type'];
  String get message => json['message'];
779
  String get code => json['code'];
780 781 782 783 784 785

  String get file => json['location']['file'];
  int get startLine => json['location']['startLine'];
  int get startColumn => json['location']['startColumn'];
  int get offset => json['location']['offset'];

786
  @override
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
  int compareTo(AnalysisError other) {
    // Sort in order of file path, error location, severity, and message.
    if (file != other.file)
      return file.compareTo(other.file);

    if (offset != other.offset)
      return offset - other.offset;

    int diff = other.severityLevel - severityLevel;
    if (diff != 0)
      return diff;

    return message.compareTo(other.message);
  }

802
  @override
803 804 805 806
  String toString() {
    String relativePath = path.relative(file);
    return '${severity.toLowerCase().padLeft(7)}$message$relativePath:$startLine:$startColumn';
  }
807
}