diff --git a/CHANGELOG.md b/CHANGELOG.md index db5fb0ce..e5d96864 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## 0.8.1 + +* `InvalidGenerationSourceError` added an optional `element` + parameter to support more helpful error messages. + ## 0.8.0 * **BREAKING** removed the deprecated `requireLibraryDirective` parameter in diff --git a/lib/src/generator.dart b/lib/src/generator.dart index 8317e446..fc89c94b 100644 --- a/lib/src/generator.dart +++ b/lib/src/generator.dart @@ -4,9 +4,11 @@ import 'dart:async'; +import 'package:analyzer/dart/element/element.dart'; import 'package:build/build.dart'; import 'library.dart'; +import 'span_for_element.dart'; /// A tool to generate Dart code based on a Dart library source. /// @@ -36,9 +38,25 @@ class InvalidGenerationSourceError extends Error { /// May be an empty string if unknown. final String todo; - InvalidGenerationSourceError(this.message, {String todo}) + /// The code element associated with this error. + /// + /// May be `null` if the error had no associated element. + final Element element; + + InvalidGenerationSourceError(this.message, {String todo, this.element}) : this.todo = todo ?? ''; @override - String toString() => message; + String toString() { + var buffer = new StringBuffer(message); + + if (element != null) { + var span = spanForElement(element); + buffer.writeln(); + buffer.writeln(span.start.toolString); + buffer.write(span.highlight()); + } + + return buffer.toString(); + } } diff --git a/pubspec.yaml b/pubspec.yaml index 55de30ef..007b7309 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,5 +1,5 @@ name: source_gen -version: 0.8.0 +version: 0.8.1-dev author: Dart Team description: Automated source code generation for Dart. homepage: https://github.com/dart-lang/source_gen diff --git a/test/builder_test.dart b/test/builder_test.dart index 8e739dd8..ba3e77d2 100644 --- a/test/builder_test.dart +++ b/test/builder_test.dart @@ -343,6 +343,9 @@ part of test_lib; // ************************************************************************** // Error: Don't use classes with the word 'Error' in the name +// package:pkg/test_lib.dart:4:7 +// class MyGoodError { } +// ^^^^^^^^^^^ // TODO: Rename MyGoodError to something else. '''; diff --git a/test/src/comment_generator.dart b/test/src/comment_generator.dart index f4b8999f..2d8ef976 100644 --- a/test/src/comment_generator.dart +++ b/test/src/comment_generator.dart @@ -29,7 +29,8 @@ class CommentGenerator extends Generator { if (classElement.displayName.contains('GoodError')) { throw new InvalidGenerationSourceError( "Don't use classes with the word 'Error' in the name", - todo: 'Rename ${classElement.displayName} to something else.'); + todo: 'Rename ${classElement.displayName} to something else.', + element: classElement); } output.writeln('// Code for "$classElement"'); }