analyze_once.dart 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
// 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';
import 'dart:collection';

import 'package:args/args.dart';

10
import '../base/common.dart';
11
import '../base/file_system.dart';
12
import '../base/process.dart';
13
import '../base/utils.dart';
14 15 16 17 18 19 20 21 22 23 24 25
import '../cache.dart';
import '../dart/analysis.dart';
import '../globals.dart';
import 'analyze.dart';
import 'analyze_base.dart';

bool isDartFile(FileSystemEntity entry) => entry is File && entry.path.endsWith('.dart');

typedef bool FileFilter(FileSystemEntity entity);

/// An aspect of the [AnalyzeCommand] to perform once time analysis.
class AnalyzeOnce extends AnalyzeBase {
26 27 28 29
  AnalyzeOnce(ArgResults argResults, this.repoPackages, {
    this.workingDirectory,
    this.previewDart2: false,
  }) : super(argResults);
30

31 32
  final List<Directory> repoPackages;

33 34
  /// The working directory for testing analysis using dartanalyzer
  final Directory workingDirectory;
35

36 37
  final bool previewDart2;

38
  @override
39
  Future<Null> analyze() async {
40 41 42
    final Stopwatch stopwatch = new Stopwatch()..start();
    final Set<Directory> pubSpecDirectories = new HashSet<Directory>();
    final List<File> dartFiles = <File>[];
43
    for (String file in argResults.rest.toList()) {
44
      file = fs.path.normalize(fs.path.absolute(file));
45
      final String root = fs.path.rootPrefix(file);
46
      dartFiles.add(fs.file(file));
47
      while (file != root) {
48 49
        file = fs.path.dirname(file);
        if (fs.isFileSync(fs.path.join(file, 'pubspec.yaml'))) {
50
          pubSpecDirectories.add(fs.directory(file));
51 52 53 54 55
          break;
        }
      }
    }

56
    final bool currentPackage = argResults['current-package'] && (argResults.wasParsed('current-package') || dartFiles.isEmpty);
57
    final bool flutterRepo = argResults['flutter-repo'] || (workingDirectory == null && inRepo(argResults.rest));
58

59 60 61 62 63
    // Use dartanalyzer directly except when analyzing the Flutter repository.
    // Analyzing the repository requires a more complex report than dartanalyzer
    // currently supports (e.g. missing member dartdoc summary).
    // TODO(danrubel): enhance dartanalyzer to provide this type of summary
    if (!flutterRepo) {
64 65 66
      if (argResults['dartdocs'])
        throwToolExit('The --dartdocs option is currently only supported with --flutter-repo.');

67 68
      final List<String> arguments = <String>[];
      arguments.addAll(dartFiles.map((FileSystemEntity f) => f.path));
69

70 71 72 73 74 75 76 77
      if (arguments.isEmpty || currentPackage) {
        // workingDirectory is non-null only when testing flutter analyze
        final Directory currentDirectory = workingDirectory ?? fs.currentDirectory.absolute;
        final Directory projectDirectory = await projectDirectoryContaining(currentDirectory);
        if (projectDirectory != null) {
          arguments.add(projectDirectory.path);
        } else if (arguments.isEmpty) {
          arguments.add(currentDirectory.path);
78 79 80
        }
      }

81 82 83 84 85 86 87 88 89
      // If the files being analyzed are outside of the current directory hierarchy
      // then dartanalyzer does not yet know how to find the ".packages" file.
      // TODO(danrubel): fix dartanalyzer to find the .packages file
      final File packagesFile = await packagesFileFor(arguments);
      if (packagesFile != null) {
        arguments.insert(0, '--packages');
        arguments.insert(1, packagesFile.path);
      }

90 91
      if (previewDart2) {
        arguments.add('--preview-dart-2');
92 93
      } else {
        arguments.add('--no-preview-dart-2');
94 95
      }

96 97 98
      final String dartanalyzer = fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dartanalyzer');
      arguments.insert(0, dartanalyzer);
      bool noErrors = false;
99
      final Set<String> issues = new Set<String>();
100 101 102 103
      int exitCode = await runCommandAndStreamOutput(
          arguments,
          workingDirectory: workingDirectory?.path,
          mapFunction: (String line) {
104 105 106 107 108 109
            // De-duplicate the dartanalyzer command output (https://github.com/dart-lang/sdk/issues/25697).
            if (line.startsWith('  ')) {
              if (!issues.add(line.trim()))
                return null;
            }

110 111 112 113 114
            // Workaround for the fact that dartanalyzer does not exit with a non-zero exit code
            // when errors are found.
            // TODO(danrubel): Fix dartanalyzer to return non-zero exit code
            if (line == 'No issues found!')
              noErrors = true;
115 116 117 118 119 120

            // Remove text about the issue count ('2 hints found.'); with the duplicates
            // above, the printed count would be incorrect.
            if (line.endsWith(' found.'))
              return null;

121 122 123 124
            return line;
          },
      );
      stopwatch.stop();
125 126
      if (issues.isNotEmpty)
        printStatus('${issues.length} ${pluralize('issue', issues.length)} found.');
127 128 129 130 131 132 133 134 135 136
      final String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
      // Workaround for the fact that dartanalyzer does not exit with a non-zero exit code
      // when errors are found.
      // TODO(danrubel): Fix dartanalyzer to return non-zero exit code
      if (exitCode == 0 && !noErrors)
        exitCode = 1;
      if (exitCode != 0)
        throwToolExit('(Ran in ${elapsed}s)', exitCode: exitCode);
      printStatus('Ran in ${elapsed}s');
      return;
137 138
    }

139 140 141
    for (Directory dir in repoPackages) {
      _collectDartFiles(dir, dartFiles);
      pubSpecDirectories.add(dir);
142 143 144
    }

    // determine what all the various .packages files depend on
145
    final PackageDependencyTracker dependencies = new PackageDependencyTracker();
146
    dependencies.checkForConflictingDependencies(pubSpecDirectories, dependencies);
147
    final Map<String, String> packages = dependencies.asPackageMap();
148 149 150 151 152

    Cache.releaseLockEarly();

    if (argResults['preamble']) {
      if (dartFiles.length == 1) {
153
        logger.printStatus('Analyzing ${fs.path.relative(dartFiles.first.path)}...');
154 155 156 157
      } else {
        logger.printStatus('Analyzing ${dartFiles.length} files...');
      }
    }
158
    final DriverOptions options = new DriverOptions();
159 160
    options.dartSdkPath = argResults['dart-sdk'];
    options.packageMap = packages;
161
    options.analysisOptionsFile = fs.path.join(Cache.flutterRoot, 'analysis_options_repo.yaml');
162
    final AnalysisDriver analyzer = new AnalysisDriver(options);
163 164

    // TODO(pq): consider error handling
165
    final List<AnalysisErrorDescription> errors = analyzer.analyze(dartFiles);
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

    int errorCount = 0;
    int membersMissingDocumentation = 0;
    for (AnalysisErrorDescription error in errors) {
      bool shouldIgnore = false;
      if (error.errorCode.name == 'public_member_api_docs') {
        // https://github.com/dart-lang/linter/issues/208
        if (isFlutterLibrary(error.source.fullName)) {
          if (!argResults['dartdocs']) {
            membersMissingDocumentation += 1;
            shouldIgnore = true;
          }
        } else {
          shouldIgnore = true;
        }
      }
      if (shouldIgnore)
        continue;
      printError(error.asString());
      errorCount += 1;
    }
187
    dumpErrors(errors.map<String>((AnalysisErrorDescription error) => error.asString()));
188 189

    stopwatch.stop();
190
    final String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1);
191 192 193 194 195

    if (isBenchmarking)
      writeBenchmark(stopwatch, errorCount, membersMissingDocumentation);

    if (errorCount > 0) {
196
      // we consider any level of error to be an error exit (we don't report different levels)
197
      if (membersMissingDocumentation > 0)
198
        throwToolExit('[lint] $membersMissingDocumentation public ${ membersMissingDocumentation == 1 ? "member lacks" : "members lack" } documentation (ran in ${elapsed}s)');
199
      else
200
        throwToolExit('(Ran in ${elapsed}s)');
201 202
    }
    if (argResults['congratulate']) {
203
      if (membersMissingDocumentation > 0) {
204 205 206 207 208 209 210
        printStatus('No analyzer warnings! (ran in ${elapsed}s; $membersMissingDocumentation public ${ membersMissingDocumentation == 1 ? "member lacks" : "members lack" } documentation)');
      } else {
        printStatus('No analyzer warnings! (ran in ${elapsed}s)');
      }
    }
  }

211 212 213 214 215 216 217 218 219 220 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 252 253 254 255 256 257 258
  /// Return a path to the ".packages" file for use by dartanalyzer when analyzing the specified files.
  /// Report an error if there are file paths that belong to different projects.
  Future<File> packagesFileFor(List<String> filePaths) async {
    String projectPath = await projectPathContaining(filePaths.first);
    if (projectPath != null) {
      if (projectPath.endsWith(fs.path.separator))
        projectPath = projectPath.substring(0, projectPath.length - 1);
      final String projectPrefix = projectPath + fs.path.separator;
      // Assert that all file paths are contained in the same project directory
      for (String filePath in filePaths) {
        if (!filePath.startsWith(projectPrefix) && filePath != projectPath)
          throwToolExit('Files in different projects cannot be analyzed at the same time.\n'
              '  Project: $projectPath\n  File outside project:  $filePath');
      }
    } else {
      // Assert that all file paths are not contained in any project
      for (String filePath in filePaths) {
        final String otherProjectPath = await projectPathContaining(filePath);
        if (otherProjectPath != null)
          throwToolExit('Files inside a project cannot be analyzed at the same time as files not in any project.\n'
              '  File inside a project: $filePath');
      }
    }

    if (projectPath == null)
      return null;
    final File packagesFile = fs.file(fs.path.join(projectPath, '.packages'));
    return await packagesFile.exists() ? packagesFile : null;
  }

  Future<String> projectPathContaining(String targetPath) async {
    final FileSystemEntity target = await fs.isDirectory(targetPath) ? fs.directory(targetPath) : fs.file(targetPath);
    final Directory projectDirectory = await projectDirectoryContaining(target);
    return projectDirectory?.path;
  }

  Future<Directory> projectDirectoryContaining(FileSystemEntity entity) async {
    Directory dir = entity is Directory ? entity : entity.parent;
    dir = dir.absolute;
    while (!await dir.childFile('pubspec.yaml').exists()) {
      final Directory parent = dir.parent;
      if (parent == null || parent.path == dir.path)
        return null;
      dir = parent;
    }
    return dir;
  }

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
  List<String> flutterRootComponents;
  bool isFlutterLibrary(String filename) {
    flutterRootComponents ??= fs.path.normalize(fs.path.absolute(Cache.flutterRoot)).split(fs.path.separator);
    final List<String> filenameComponents = fs.path.normalize(fs.path.absolute(filename)).split(fs.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;
  }

278
  List<File> _collectDartFiles(Directory dir, List<File> collected) {
279
    // Bail out in case of a .dartignore.
280
    if (fs.isFileSync(fs.path.join(dir.path, '.dartignore')))
281 282 283
      return collected;

    for (FileSystemEntity entity in dir.listSync(recursive: false, followLinks: false)) {
284
      if (isDartFile(entity))
285 286
        collected.add(entity);
      if (entity is Directory) {
287
        final String name = fs.path.basename(entity.path);
288
        if (!name.startsWith('.') && name != 'packages')
289
          _collectDartFiles(entity, collected);
290 291 292 293 294 295
      }
    }

    return collected;
  }
}