diff --git a/dev/bots/test.sh b/dev/bots/test.sh index 0ae9f9d627..5692684755 100755 --- a/dev/bots/test.sh +++ b/dev/bots/test.sh @@ -45,7 +45,7 @@ SRC_ROOT=$PWD # generate and analyze our large sample app dart dev/tools/mega_gallery.dart -(cd dev/benchmarks/mega_gallery; flutter analyze --watch --benchmark) +(cd dev/benchmarks/mega_gallery; flutter watch --benchmark) if [ -n "$COVERAGE_FLAG" ]; then GSUTIL=$HOME/google-cloud-sdk/bin/gsutil diff --git a/packages/flutter_tools/lib/executable.dart b/packages/flutter_tools/lib/executable.dart index 988a2056f7..b32b9be3d8 100644 --- a/packages/flutter_tools/lib/executable.dart +++ b/packages/flutter_tools/lib/executable.dart @@ -38,6 +38,7 @@ import 'src/commands/test.dart'; import 'src/commands/trace.dart'; import 'src/commands/update_packages.dart'; import 'src/commands/upgrade.dart'; +import 'src/commands/watch.dart'; import 'src/device.dart'; import 'src/doctor.dart'; import 'src/globals.dart'; @@ -84,7 +85,8 @@ Future main(List args) async { ..addCommand(new TestCommand()) ..addCommand(new TraceCommand()) ..addCommand(new UpdatePackagesCommand(hidden: !verboseHelp)) - ..addCommand(new UpgradeCommand()); + ..addCommand(new UpgradeCommand()) + ..addCommand(new WatchCommand(verboseHelp: verboseHelp)); return Chain.capture/*>*/(() async { // Initialize globals. diff --git a/packages/flutter_tools/lib/src/commands/analysis_common.dart b/packages/flutter_tools/lib/src/commands/analysis_common.dart new file mode 100644 index 0000000000..5c1aaa9fff --- /dev/null +++ b/packages/flutter_tools/lib/src/commands/analysis_common.dart @@ -0,0 +1,68 @@ +// 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:io'; + +import '../base/utils.dart'; +import '../globals.dart'; +import '../runner/flutter_command.dart'; + +/// Common behavior for `flutter analyze` and `flutter watch` +abstract class AnalysisCommand extends FlutterCommand { + AnalysisCommand({bool verboseHelp: false}) { + 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); + argParser.addFlag('dartdocs', help: 'List every public member that is lacking documentation (only examines files in the Flutter repository).', defaultsTo: false); + argParser.addOption('write', valueHelp: 'file', help: 'Also output the results to a file.'); + argParser.addOption('dart-sdk', valueHelp: 'path-to-sdk', help: 'The path to the Dart SDK.', hide: !verboseHelp); + + // Hidden option to enable a benchmarking mode. + argParser.addFlag('benchmark', negatable: false, hide: !verboseHelp, help: 'Also output the analysis time'); + + usesPubOption(); + } + + @override + bool get shouldRunPub { + // If they're not analyzing the current project. + if (!argResults['current-package']) + return false; + + // Or we're not in a project directory. + if (!new File('pubspec.yaml').existsSync()) + return false; + + return super.shouldRunPub; + } + + void dumpErrors(Iterable errors) { + if (argResults['write'] != null) { + try { + final RandomAccessFile resultsFile = new File(argResults['write']).openSync(mode: FileMode.WRITE); + try { + resultsFile.lockSync(); + resultsFile.writeStringSync(errors.join('\n')); + } finally { + resultsFile.close(); + } + } catch (e) { + printError('Failed to save output to "${argResults['write']}": $e'); + } + } + } + + void writeBenchmark(Stopwatch stopwatch, int errorCount, int membersMissingDocumentation) { + final String benchmarkOut = 'analysis_benchmark.json'; + Map data = { + 'time': (stopwatch.elapsedMilliseconds / 1000.0), + 'issues': errorCount, + 'missingDartDocs': membersMissingDocumentation + }; + new File(benchmarkOut).writeAsStringSync(toPrettyJson(data)); + printStatus('Analysis benchmark written to $benchmarkOut ($data).'); + } + + bool get isBenchmarking => argResults['benchmark']; +} \ No newline at end of file diff --git a/packages/flutter_tools/lib/src/commands/analyze.dart b/packages/flutter_tools/lib/src/commands/analyze.dart index 3f27e93e04..b2b8d0eeb4 100644 --- a/packages/flutter_tools/lib/src/commands/analyze.dart +++ b/packages/flutter_tools/lib/src/commands/analyze.dart @@ -4,40 +4,24 @@ import 'dart:async'; import 'dart:collection'; -import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:yaml/yaml.dart' as yaml; -import '../base/logger.dart'; -import '../base/utils.dart'; import '../cache.dart'; import '../dart/analysis.dart'; -import '../dart/sdk.dart'; import '../globals.dart'; -import '../runner/flutter_command.dart'; +import 'analysis_common.dart'; bool isDartFile(FileSystemEntity entry) => entry is File && entry.path.endsWith('.dart'); typedef bool FileFilter(FileSystemEntity entity); -class AnalyzeCommand extends FlutterCommand { - AnalyzeCommand({bool verboseHelp: false}) { - 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); - argParser.addFlag('dartdocs', help: 'List every public member that is lacking documentation (only examines files in the Flutter repository).', defaultsTo: false); - argParser.addFlag('preamble', help: 'Display the number of files that will be analyzed.', defaultsTo: true); +class AnalyzeCommand extends AnalysisCommand { + AnalyzeCommand({bool verboseHelp: false}) : super(verboseHelp: verboseHelp) { argParser.addFlag('congratulate', help: 'Show output even when there are no errors, warnings, hints, or lints.', defaultsTo: true); - argParser.addFlag('watch', help: 'Run analysis continuously, watching the filesystem for changes.', negatable: false); - argParser.addOption('write', valueHelp: 'file', help: 'Also output the results to a file. This is useful with --watch if you want a file to always contain the latest results.'); - argParser.addOption('dart-sdk', valueHelp: 'path-to-sdk', help: 'The path to the Dart SDK.', hide: !verboseHelp); - - // Hidden option to enable a benchmarking mode. - argParser.addFlag('benchmark', negatable: false, hide: !verboseHelp); - - usesPubOption(); + argParser.addFlag('preamble', help: 'Display the number of files that will be analyzed.', defaultsTo: true); } @override @@ -47,58 +31,7 @@ class AnalyzeCommand extends FlutterCommand { String get description => 'Analyze the project\'s Dart code.'; @override - bool get shouldRunPub { - // If they're not analyzing the current project. - if (!argResults['current-package']) - return false; - - // Or we're not in a project directory. - if (!new File('pubspec.yaml').existsSync()) - return false; - - return super.shouldRunPub; - } - - @override - Future runCommand() => argResults['watch'] ? _analyzeWatch() : _analyzeOnce(); - - List flutterRootComponents; - bool isFlutterLibrary(String filename) { - flutterRootComponents ??= path.normalize(path.absolute(Cache.flutterRoot)).split(path.separator); - List 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; - } - - /// Return `true` if [fileList] contains a path that resides inside the Flutter repository. - /// If [fileList] is empty, then return `true` if the current directory resides inside the Flutter repository. - bool inRepo(List fileList) { - if (fileList == null || fileList.isEmpty) - fileList = [path.current]; - String root = path.normalize(path.absolute(Cache.flutterRoot)); - String prefix = root + Platform.pathSeparator; - for (String file in fileList) { - file = path.normalize(path.absolute(file)); - if (file == root || file.startsWith(prefix)) - return true; - } - return false; - } - - bool get _isBenchmarking => argResults['benchmark']; - - Future _analyzeOnce() async { + Future runCommand() async { Stopwatch stopwatch = new Stopwatch()..start(); Set pubSpecDirectories = new HashSet(); List dartFiles = []; @@ -188,7 +121,7 @@ class AnalyzeCommand extends FlutterCommand { if (packageName != 'analyzer' || packagePath.startsWith('..')) dependencies.add(packageName, path.normalize(path.absolute(directory.path, path.fromUri(packagePath))), dotPackagesPath); } - }); + }); } } @@ -216,8 +149,8 @@ class AnalyzeCommand extends FlutterCommand { options.dartSdkPath = argResults['dart-sdk']; options.packageMap = packages; options.analysisOptionsFile = flutterRepo - ? path.join(Cache.flutterRoot, '.analysis_options_repo') - : path.join(Cache.flutterRoot, '.analysis_options_user'); + ? path.join(Cache.flutterRoot, '.analysis_options_repo') + : path.join(Cache.flutterRoot, '.analysis_options_user'); AnalysisDriver analyzer = new AnalysisDriver(options); // TODO(pq): consider error handling @@ -247,13 +180,13 @@ class AnalyzeCommand extends FlutterCommand { printError(error.asString()); errorCount += 1; } - _dumpErrors(errors.map/**/((AnalysisErrorDescription error) => error.asString())); + dumpErrors(errors.map/**/((AnalysisErrorDescription error) => error.asString())); stopwatch.stop(); String elapsed = (stopwatch.elapsedMilliseconds / 1000.0).toStringAsFixed(1); - if (_isBenchmarking) - _writeBenchmark(stopwatch, errorCount, membersMissingDocumentation); + if (isBenchmarking) + writeBenchmark(stopwatch, errorCount, membersMissingDocumentation); if (errorCount > 0) { if (membersMissingDocumentation > 0 && flutterRepo) @@ -272,20 +205,38 @@ class AnalyzeCommand extends FlutterCommand { return 0; } - void _dumpErrors(Iterable errors) { - if (argResults['write'] != null) { - try { - final RandomAccessFile resultsFile = new File(argResults['write']).openSync(mode: FileMode.WRITE); - try { - resultsFile.lockSync(); - resultsFile.writeStringSync(errors.join('\n')); - } finally { - resultsFile.close(); - } - } catch (e) { - printError('Failed to save output to "${argResults['write']}": $e'); - } + List flutterRootComponents; + bool isFlutterLibrary(String filename) { + flutterRootComponents ??= path.normalize(path.absolute(Cache.flutterRoot)).split(path.separator); + List 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; + } + + /// Return `true` if [fileList] contains a path that resides inside the Flutter repository. + /// If [fileList] is empty, then return `true` if the current directory resides inside the Flutter repository. + bool inRepo(List fileList) { + if (fileList == null || fileList.isEmpty) + fileList = [path.current]; + String root = path.normalize(path.absolute(Cache.flutterRoot)); + String prefix = root + Platform.pathSeparator; + for (String file in fileList) { + file = path.normalize(path.absolute(file)); + if (file == root || file.startsWith(prefix)) + return true; + } + return false; } List _collectDartFiles(Directory dir, List collected, {FileFilter exclude}) { @@ -305,134 +256,6 @@ class AnalyzeCommand extends FlutterCommand { return collected; } - - - String analysisTarget; - bool firstAnalysis = true; - Set analyzedPaths = new Set(); - Map> analysisErrors = >{}; - Stopwatch analysisTimer; - int lastErrorCount = 0; - Status analysisStatus; - - Future _analyzeWatch() async { - List directories; - - if (argResults['flutter-repo']) { - directories = runner.getRepoAnalysisEntryPoints().map((Directory dir) => dir.path).toList(); - analysisTarget = 'Flutter repository'; - printTrace('Analyzing Flutter repository:'); - for (String projectPath in directories) - printTrace(' ${path.relative(projectPath)}'); - } else { - directories = [Directory.current.path]; - analysisTarget = Directory.current.path; - } - - AnalysisServer server = new AnalysisServer(dartSdkPath, directories); - server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing)); - server.onErrors.listen(_handleAnalysisErrors); - - Cache.releaseLockEarly(); - - await server.start(); - final int exitCode = await server.onExit; - - printStatus('Analysis server exited with code $exitCode.'); - return 0; - } - - void _handleAnalysisStatus(AnalysisServer server, bool isAnalyzing) { - if (isAnalyzing) { - analysisStatus?.cancel(); - if (!firstAnalysis) - printStatus('\n'); - analysisStatus = logger.startProgress('Analyzing $analysisTarget...'); - analyzedPaths.clear(); - analysisTimer = new Stopwatch()..start(); - } else { - analysisStatus?.stop(showElapsedTime: true); - analysisTimer.stop(); - - logger.printStatus(terminal.clearScreen(), newline: false); - - // Remove errors for deleted files, sort, and print errors. - final List errors = []; - for (String path in analysisErrors.keys.toList()) { - if (FileSystemEntity.isFileSync(path)) { - errors.addAll(analysisErrors[path]); - } else { - analysisErrors.remove(path); - } - } - - errors.sort(); - - for (AnalysisError error in errors) { - printStatus(error.toString()); - if (error.code != null) - printTrace('error code: ${error.code}'); - } - - _dumpErrors(errors.map/**/((AnalysisError error) => error.toLegacyString())); - - // 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 = '$issueCount ${pluralize('issue', issueCount)} found ($issueDiff new)'; - else if (issueDiff < 0) - errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found (${-issueDiff} fixed)'; - else if (issueCount != 0) - errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found'; - 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'); - - if (firstAnalysis && _isBenchmarking) { - _writeBenchmark(analysisTimer, issueCount, -1); // TODO(ianh): track members missing dartdocs instead of saying -1 - server.dispose().then((_) => exit(issueCount > 0 ? 1 : 0)); - } - - 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; - } - - void _writeBenchmark(Stopwatch stopwatch, int errorCount, int membersMissingDocumentation) { - final String benchmarkOut = 'analysis_benchmark.json'; - Map data = { - 'time': (stopwatch.elapsedMilliseconds / 1000.0), - 'issues': errorCount, - 'missingDartDocs': membersMissingDocumentation - }; - new File(benchmarkOut).writeAsStringSync(toPrettyJson(data)); - printStatus('Analysis benchmark written to $benchmarkOut ($data).'); - } } class PackageDependency { @@ -523,179 +346,3 @@ class PackageDependencyTracker { return result; } } - -class AnalysisServer { - AnalysisServer(this.sdk, this.directories); - - final String sdk; - final List directories; - - Process _process; - StreamController _analyzingController = new StreamController.broadcast(); - StreamController _errorsController = new StreamController.broadcast(); - - int _id = 0; - - Future start() async { - String snapshot = path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot'); - List args = [snapshot, '--sdk', sdk]; - - printTrace('dart ${args.join(' ')}'); - _process = await Process.start(path.join(dartSdkPath, 'bin', 'dart'), args); - _process.exitCode.whenComplete(() => _process = null); - - Stream errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()); - errorStream.listen((String error) => printError(error)); - - Stream 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', { - 'options': { - 'enableSuperMixins': true - } - }); - - _sendCommand('server.setSubscriptions', { - 'subscriptions': ['STATUS'] - }); - - _sendCommand('analysis.setAnalysisRoots', { - 'included': directories, - 'excluded': [] - }); - } - - Stream get onAnalyzing => _analyzingController.stream; - Stream get onErrors => _errorsController.stream; - - Future get onExit => _process.exitCode; - - void _sendCommand(String method, Map params) { - String message = JSON.encode( { - 'id': (++_id).toString(), - 'method': method, - 'params': params - }); - _process.stdin.writeln(message); - printTrace('==> $message'); - } - - void _handleServerResponse(String line) { - printTrace('<== $line'); - - dynamic response = JSON.decode(line); - - if (response is Map) { - if (response['event'] != null) { - String event = response['event']; - dynamic params = response['params']; - - if (params is Map) { - 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) { - // Fields are 'code', 'message', and 'stackTrace'. - Map error = response['error']; - printError('Error response from the server: ${error['code']} ${error['message']}'); - if (error['stackTrace'] != null) - printError(error['stackTrace']); - } - } - } - - void _handleStatus(Map statusInfo) { - // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}} - if (statusInfo['analysis'] != null) { - bool isAnalyzing = statusInfo['analysis']['isAnalyzing']; - _analyzingController.add(isAnalyzing); - } - } - - void _handleServerError(Map error) { - // Fields are 'isFatal', 'message', and 'stackTrace'. - printError('Error from the analysis server: ${error['message']}'); - if (error['stackTrace'] != null) - printError(error['stackTrace']); - } - - void _handleAnalysisIssues(Map issueInfo) { - // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} - String file = issueInfo['file']; - List errors = issueInfo['errors'].map((Map json) => new AnalysisError(json)).toList(); - _errorsController.add(new FileAnalysisErrors(file, errors)); - } - - Future dispose() async { - await _analyzingController.close(); - await _errorsController.close(); - return _process?.kill(); - } -} - -class FileAnalysisErrors { - FileAnalysisErrors(this.file, this.errors); - - final String file; - final List errors; -} - -class AnalysisError implements Comparable { - AnalysisError(this.json); - - static final Map _severityMap = { - '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 json; - - String get severity => json['severity']; - int get severityLevel => _severityMap[severity] ?? 0; - String get type => json['type']; - String get message => json['message']; - String get code => json['code']; - - String get file => json['location']['file']; - int get startLine => json['location']['startLine']; - int get startColumn => json['location']['startColumn']; - int get offset => json['location']['offset']; - - @override - 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); - } - - @override - String toString() { - String relativePath = path.relative(file); - return '${severity.toLowerCase().padLeft(7)} • $message • $relativePath:$startLine:$startColumn'; - } - - String toLegacyString() { - return '[${severity.toLowerCase()}] $message ($file:$startLine:$startColumn)'; - } -} diff --git a/packages/flutter_tools/lib/src/commands/watch.dart b/packages/flutter_tools/lib/src/commands/watch.dart new file mode 100644 index 0000000000..0c6f84d3fb --- /dev/null +++ b/packages/flutter_tools/lib/src/commands/watch.dart @@ -0,0 +1,319 @@ +// 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:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as path; + +import '../base/logger.dart'; +import '../base/utils.dart'; +import '../cache.dart'; +import '../dart/sdk.dart'; +import '../globals.dart'; +import 'analysis_common.dart'; + +class WatchCommand extends AnalysisCommand { + WatchCommand({bool verboseHelp: false}) : super(verboseHelp: verboseHelp); + + @override + String get name => 'watch'; + + @override + String get description => 'Analyze the project\'s Dart code continuously, watching the filesystem for changes.'; + + String analysisTarget; + bool firstAnalysis = true; + Set analyzedPaths = new Set(); + Map> analysisErrors = >{}; + Stopwatch analysisTimer; + int lastErrorCount = 0; + Status analysisStatus; + + @override + Future runCommand() async { + List directories; + + if (argResults['flutter-repo']) { + directories = runner.getRepoAnalysisEntryPoints().map((Directory dir) => dir.path).toList(); + analysisTarget = 'Flutter repository'; + printTrace('Analyzing Flutter repository:'); + for (String projectPath in directories) + printTrace(' ${path.relative(projectPath)}'); + } else { + directories = [Directory.current.path]; + analysisTarget = Directory.current.path; + } + + AnalysisServer server = new AnalysisServer(dartSdkPath, directories); + server.onAnalyzing.listen((bool isAnalyzing) => _handleAnalysisStatus(server, isAnalyzing)); + server.onErrors.listen(_handleAnalysisErrors); + + Cache.releaseLockEarly(); + + await server.start(); + final int exitCode = await server.onExit; + + printStatus('Analysis server exited with code $exitCode.'); + return 0; + } + + void _handleAnalysisStatus(AnalysisServer server, bool isAnalyzing) { + if (isAnalyzing) { + analysisStatus?.cancel(); + if (!firstAnalysis) + printStatus('\n'); + analysisStatus = logger.startProgress('Analyzing $analysisTarget...'); + analyzedPaths.clear(); + analysisTimer = new Stopwatch()..start(); + } else { + analysisStatus?.stop(showElapsedTime: true); + analysisTimer.stop(); + + logger.printStatus(terminal.clearScreen(), newline: false); + + // Remove errors for deleted files, sort, and print errors. + final List errors = []; + for (String path in analysisErrors.keys.toList()) { + if (FileSystemEntity.isFileSync(path)) { + errors.addAll(analysisErrors[path]); + } else { + analysisErrors.remove(path); + } + } + + errors.sort(); + + for (AnalysisError error in errors) { + printStatus(error.toString()); + if (error.code != null) + printTrace('error code: ${error.code}'); + } + + dumpErrors(errors.map/**/((AnalysisError error) => error.toLegacyString())); + + // 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 = '$issueCount ${pluralize('issue', issueCount)} found ($issueDiff new)'; + else if (issueDiff < 0) + errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found (${-issueDiff} fixed)'; + else if (issueCount != 0) + errorsMessage = '$issueCount ${pluralize('issue', issueCount)} found'; + 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'); + + if (firstAnalysis && isBenchmarking) { + writeBenchmark(analysisTimer, issueCount, -1); // TODO(ianh): track members missing dartdocs instead of saying -1 + server.dispose().then((_) => exit(issueCount > 0 ? 1 : 0)); + } + + firstAnalysis = false; + } + } + + bool _filterError(AnalysisError error) { + // TODO(devoncarew): Also filter the regex items from `analyzeOnce()`. + + if (error.type == 'TODO') + return true; + + return false; + } + + void _handleAnalysisErrors(FileAnalysisErrors fileErrors) { + fileErrors.errors.removeWhere(_filterError); + + analyzedPaths.add(fileErrors.file); + analysisErrors[fileErrors.file] = fileErrors.errors; + } +} + +class AnalysisServer { + AnalysisServer(this.sdk, this.directories); + + final String sdk; + final List directories; + + Process _process; + StreamController _analyzingController = new StreamController.broadcast(); + StreamController _errorsController = new StreamController.broadcast(); + + int _id = 0; + + Future start() async { + String snapshot = path.join(sdk, 'bin/snapshots/analysis_server.dart.snapshot'); + List args = [snapshot, '--sdk', sdk]; + + printTrace('dart ${args.join(' ')}'); + _process = await Process.start(path.join(dartSdkPath, 'bin', 'dart'), args); + _process.exitCode.whenComplete(() => _process = null); + + Stream errorStream = _process.stderr.transform(UTF8.decoder).transform(const LineSplitter()); + errorStream.listen((String error) => printError(error)); + + Stream 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', { + 'options': { + 'enableSuperMixins': true + } + }); + + _sendCommand('server.setSubscriptions', { + 'subscriptions': ['STATUS'] + }); + + _sendCommand('analysis.setAnalysisRoots', { + 'included': directories, + 'excluded': [] + }); + } + + Stream get onAnalyzing => _analyzingController.stream; + Stream get onErrors => _errorsController.stream; + + Future get onExit => _process.exitCode; + + void _sendCommand(String method, Map params) { + String message = JSON.encode( { + 'id': (++_id).toString(), + 'method': method, + 'params': params + }); + _process.stdin.writeln(message); + printTrace('==> $message'); + } + + void _handleServerResponse(String line) { + printTrace('<== $line'); + + dynamic response = JSON.decode(line); + + if (response is Map) { + if (response['event'] != null) { + String event = response['event']; + dynamic params = response['params']; + + if (params is Map) { + 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) { + // Fields are 'code', 'message', and 'stackTrace'. + Map error = response['error']; + printError('Error response from the server: ${error['code']} ${error['message']}'); + if (error['stackTrace'] != null) + printError(error['stackTrace']); + } + } + } + + void _handleStatus(Map statusInfo) { + // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}} + if (statusInfo['analysis'] != null) { + bool isAnalyzing = statusInfo['analysis']['isAnalyzing']; + _analyzingController.add(isAnalyzing); + } + } + + void _handleServerError(Map error) { + // Fields are 'isFatal', 'message', and 'stackTrace'. + printError('Error from the analysis server: ${error['message']}'); + if (error['stackTrace'] != null) + printError(error['stackTrace']); + } + + void _handleAnalysisIssues(Map issueInfo) { + // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} + String file = issueInfo['file']; + List errors = issueInfo['errors'].map((Map json) => new AnalysisError(json)).toList(); + _errorsController.add(new FileAnalysisErrors(file, errors)); + } + + Future dispose() async { + await _analyzingController.close(); + await _errorsController.close(); + return _process?.kill(); + } +} + +class AnalysisError implements Comparable { + AnalysisError(this.json); + + static final Map _severityMap = { + '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 json; + + String get severity => json['severity']; + int get severityLevel => _severityMap[severity] ?? 0; + String get type => json['type']; + String get message => json['message']; + String get code => json['code']; + + String get file => json['location']['file']; + int get startLine => json['location']['startLine']; + int get startColumn => json['location']['startColumn']; + int get offset => json['location']['offset']; + + @override + 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); + } + + @override + String toString() { + String relativePath = path.relative(file); + return '${severity.toLowerCase().padLeft(7)} • $message • $relativePath:$startLine:$startColumn'; + } + + String toLegacyString() { + return '[${severity.toLowerCase()}] $message ($file:$startLine:$startColumn)'; + } +} + +class FileAnalysisErrors { + FileAnalysisErrors(this.file, this.errors); + + final String file; + final List errors; +} diff --git a/packages/flutter_tools/test/analyze_test.dart b/packages/flutter_tools/test/analyze_test.dart index 95100a4bc8..8decda8301 100644 --- a/packages/flutter_tools/test/analyze_test.dart +++ b/packages/flutter_tools/test/analyze_test.dart @@ -2,14 +2,10 @@ // 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:io'; -import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/analyze.dart'; -import 'package:flutter_tools/src/dart/pub.dart'; -import 'package:flutter_tools/src/dart/sdk.dart'; import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; @@ -17,7 +13,6 @@ import 'package:test/test.dart'; import 'src/context.dart'; void main() { - AnalysisServer server; Directory tempDir; setUp(() { @@ -27,47 +22,9 @@ void main() { tearDown(() { tempDir?.deleteSync(recursive: true); - return server?.dispose(); }); group('analyze', () { - testUsingContext('AnalysisServer success', () async { - _createSampleProject(tempDir); - - await pubGet(directory: tempDir.path); - - server = new AnalysisServer(dartSdkPath, [tempDir.path]); - - int errorCount = 0; - Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; - server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); - - await server.start(); - await onDone; - - expect(errorCount, 0); - }, overrides: { - OperatingSystemUtils: os - }); - - testUsingContext('AnalysisServer errors', () async { - _createSampleProject(tempDir, brokenCode: true); - - await pubGet(directory: tempDir.path); - - server = new AnalysisServer(dartSdkPath, [tempDir.path]); - - int errorCount = 0; - Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; - server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); - - await server.start(); - await onDone; - - expect(errorCount, 2); - }, overrides: { - OperatingSystemUtils: os - }); testUsingContext('inRepo', () { AnalyzeCommand cmd = new AnalyzeCommand(); @@ -94,19 +51,3 @@ void main() { }); }); } - -void _createSampleProject(Directory directory, { bool brokenCode: false }) { - File pubspecFile = new File(path.join(directory.path, 'pubspec.yaml')); - pubspecFile.writeAsStringSync(''' -name: foo_project -'''); - - File dartFile = new File(path.join(directory.path, 'lib', 'main.dart')); - dartFile.parent.createSync(); - dartFile.writeAsStringSync(''' -void main() { - print('hello world'); - ${brokenCode ? 'prints("hello world");' : ''} -} -'''); -} diff --git a/packages/flutter_tools/test/watch_test.dart b/packages/flutter_tools/test/watch_test.dart new file mode 100644 index 0000000000..7651c4841e --- /dev/null +++ b/packages/flutter_tools/test/watch_test.dart @@ -0,0 +1,87 @@ +// 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. + +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_tools/src/base/os.dart'; +import 'package:flutter_tools/src/commands/watch.dart'; +import 'package:flutter_tools/src/dart/pub.dart'; +import 'package:flutter_tools/src/dart/sdk.dart'; +import 'package:flutter_tools/src/runner/flutter_command_runner.dart'; +import 'package:path/path.dart' as path; +import 'package:test/test.dart'; + +import 'src/context.dart'; + +void main() { + AnalysisServer server; + Directory tempDir; + + setUp(() { + FlutterCommandRunner.initFlutterRoot(); + tempDir = Directory.systemTemp.createTempSync('analysis_test'); + }); + + tearDown(() { + tempDir?.deleteSync(recursive: true); + return server?.dispose(); + }); + + group('watch', () { + testUsingContext('AnalysisServer success', () async { + _createSampleProject(tempDir); + + await pubGet(directory: tempDir.path); + + server = new AnalysisServer(dartSdkPath, [tempDir.path]); + + int errorCount = 0; + Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; + server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); + + await server.start(); + await onDone; + + expect(errorCount, 0); + }, overrides: { + OperatingSystemUtils: os + }); + }); + + testUsingContext('AnalysisServer errors', () async { + _createSampleProject(tempDir, brokenCode: true); + + await pubGet(directory: tempDir.path); + + server = new AnalysisServer(dartSdkPath, [tempDir.path]); + + int errorCount = 0; + Future onDone = server.onAnalyzing.where((bool analyzing) => analyzing == false).first; + server.onErrors.listen((FileAnalysisErrors errors) => errorCount += errors.errors.length); + + await server.start(); + await onDone; + + expect(errorCount, 2); + }, overrides: { + OperatingSystemUtils: os + }); +} + +void _createSampleProject(Directory directory, { bool brokenCode: false }) { + File pubspecFile = new File(path.join(directory.path, 'pubspec.yaml')); + pubspecFile.writeAsStringSync(''' +name: foo_project +'''); + + File dartFile = new File(path.join(directory.path, 'lib', 'main.dart')); + dartFile.parent.createSync(); + dartFile.writeAsStringSync(''' +void main() { + print('hello world'); + ${brokenCode ? 'prints("hello world");' : ''} +} +'''); +}