analyze_once.dart 5.69 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';


8
import '../base/common.dart';
9
import '../base/file_system.dart';
10
import '../base/logger.dart';
11 12 13 14
import '../dart/analysis.dart';
import 'analyze_base.dart';

class AnalyzeOnce extends AnalyzeBase {
15
  AnalyzeOnce(
16
    super.argResults,
17 18
    List<String> repoRoots,
    List<Directory> repoPackages, {
19 20 21 22 23 24
    required super.fileSystem,
    required super.logger,
    required super.platform,
    required super.processManager,
    required super.terminal,
    required super.artifacts,
25
    this.workingDirectory,
26 27 28 29
  }) : super(
        repoRoots: repoRoots,
        repoPackages: repoPackages,
      );
30

31
  /// The working directory for testing analysis using dartanalyzer.
32
  final Directory? workingDirectory;
33 34

  @override
35
  Future<void> analyze() async {
36
    final String currentDirectory =
37
        (workingDirectory ?? fileSystem.currentDirectory).path;
38

39 40
    // find directories or files from argResults.rest
    final Set<String> items = Set<String>.of(argResults.rest
41
        .map<String>((String path) => fileSystem.path.canonicalize(path)));
42 43 44
    if (items.isNotEmpty) {
      for (final String item in items) {
        final FileSystemEntityType type = fileSystem.typeSync(item);
45

46
        if (type == FileSystemEntityType.notFound) {
47
          throwToolExit("'$item' does not exist");
48 49 50 51
        }
      }
    }

52
    if (isFlutterRepo) {
53
      // check for conflicting dependencies
54
      final PackageDependencyTracker dependencies = PackageDependencyTracker();
55
      dependencies.checkForConflictingDependencies(repoPackages, dependencies);
56
      items.addAll(repoRoots);
57
      if (argResults.wasParsed('current-package') && (argResults['current-package'] as bool)) {
58
        items.add(currentDirectory);
59
      }
60
    } else {
61 62
      if ((argResults['current-package'] as bool) && items.isEmpty) {
        items.add(currentDirectory);
63
      }
64 65
    }

66
    if (items.isEmpty) {
67
      throwToolExit('Nothing to analyze.', exitCode: 0);
68
    }
69

70
    final Completer<void> analysisCompleter = Completer<void>();
71
    final List<AnalysisError> errors = <AnalysisError>[];
72

73
    final AnalysisServer server = AnalysisServer(
74
      sdkPath,
75
      items.toList(),
76 77 78 79 80
      fileSystem: fileSystem,
      platform: platform,
      logger: logger,
      processManager: processManager,
      terminal: terminal,
81
      protocolTrafficLog: protocolTrafficLog,
82
    );
83

84 85
    Stopwatch? timer;
    Status? progress;
86
    try {
87
      StreamSubscription<bool>? subscription;
88 89

      void handleAnalysisStatus(bool isAnalyzing) {
90 91 92 93 94
        if (!isAnalyzing) {
          analysisCompleter.complete();
          subscription?.cancel();
          subscription = null;
        }
95 96 97 98 99 100 101 102 103 104 105
      }

      subscription = server.onAnalyzing.listen((bool isAnalyzing) => handleAnalysisStatus(isAnalyzing));

      void handleAnalysisErrors(FileAnalysisErrors fileErrors) {
        fileErrors.errors.removeWhere((AnalysisError error) => error.type == 'TODO');

        errors.addAll(fileErrors.errors);
      }

      server.onErrors.listen(handleAnalysisErrors);
106 107 108

      await server.start();
      // Completing the future in the callback can't fail.
109
      unawaited(server.onExit.then<void>((int? exitCode) {
110
        if (!analysisCompleter.isCompleted) {
111 112 113 114 115 116
          analysisCompleter.completeError(
            // Include the last 20 lines of server output in exception message
            Exception(
              'analysis server exited with code $exitCode and output:\n${server.getLogs(20)}',
            ),
          );
117 118 119 120 121
        }
      }));

      // collect results
      timer = Stopwatch()..start();
122 123 124
      final String message = items.length > 1
          ? '${items.length} ${items.length == 1 ? 'item' : 'items'}'
          : fileSystem.path.basename(items.first);
125
      progress = argResults['preamble'] == true
126 127 128 129 130 131 132 133 134 135 136
          ? logger.startProgress(
            'Analyzing $message...',
          )
          : null;

      await analysisCompleter.future;
    } finally {
      await server.dispose();
      progress?.cancel();
      timer?.stop();
    }
137 138

    // emit benchmarks
139
    if (isBenchmarking) {
140
      writeBenchmark(timer, errors.length);
141
    }
142

143 144
    // --write
    dumpErrors(errors.map<String>((AnalysisError error) => error.toLegacyString()));
145

146
    // report errors
147
    if (errors.isNotEmpty && (argResults['preamble'] as bool)) {
148
      logger.printStatus('');
149
    }
150
    errors.sort();
151
    for (final AnalysisError error in errors) {
152
      logger.printStatus(error.toString(), hangingIndent: 7);
153
    }
154

155
    final int errorCount = errors.length;
156
    final String seconds = (timer.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
157 158 159 160
    final String errorsMessage = AnalyzeBase.generateErrorsMessage(
      issueCount: errorCount,
      seconds: seconds,
    );
161

162
    if (errorCount > 0) {
163
      logger.printStatus('');
164
      throwToolExit(errorsMessage, exitCode: _isFatal(errors) ? 1 : 0);
165
    }
166

167 168
    if (argResults['congratulate'] as bool) {
      logger.printStatus(errorsMessage);
169 170
    }

171 172
    if (server.didServerErrorOccur) {
      throwToolExit('Server error(s) occurred. (ran in ${seconds}s)');
173
    }
174
  }
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

  bool _isFatal(List<AnalysisError> errors) {
    for (final AnalysisError error in errors) {
      final AnalysisSeverity severityLevel = error.writtenError.severityLevel;
      if (severityLevel == AnalysisSeverity.error) {
        return true;
      }
      if (severityLevel == AnalysisSeverity.warning &&
        (argResults['fatal-warnings'] as bool || argResults['fatal-infos'] as bool)) {
        return true;
      }
      if (severityLevel == AnalysisSeverity.info && argResults['fatal-infos'] as bool) {
        return true;
      }
    }
    return false;
  }
192
}