Gracefully handle invalid views list of annotation

Fixes #2636
This commit is contained in:
Simon Binder 2023-09-25 15:29:09 +02:00
parent 5f8ea09030
commit f8ba56c8e2
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
3 changed files with 24 additions and 14 deletions

View File

@ -1,3 +1,7 @@
## 2.12.1-dev
- Fix invalid types listed in `views` crashing the generator.
## 2.12.0
- Adds the static getter `$name` to generated table classes.

View File

@ -1,4 +1,5 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:collection/collection.dart';
@ -23,19 +24,25 @@ class DartAccessorResolver
final annotation = discovered.annotation;
final element = discovered.dartElement;
final rawTablesOrNull = annotation.getField('tables')?.toListValue();
if (rawTablesOrNull == null) {
final annotationName =
annotation.type?.nameIfInterfaceType ?? 'DriftDatabase';
List<DartObject> readList(String name) {
final rawTablesOrNull = annotation.getField(name)?.toListValue();
if (rawTablesOrNull == null) {
final annotationName =
annotation.type?.nameIfInterfaceType ?? 'DriftDatabase';
reportError(DriftAnalysisError.forDartElement(
element,
'Could not read tables from @$annotationName annotation! \n'
'Please make sure that all table classes exist.',
));
reportError(DriftAnalysisError.forDartElement(
element,
'Could not read $name from @$annotationName annotation! \n'
'Please make sure that all table classes exist.',
));
return const [];
} else {
return rawTablesOrNull;
}
}
for (final tableType in rawTablesOrNull ?? const []) {
for (final tableType in readList('tables')) {
final dartType = tableType.toTypeValue();
if (dartType is! InterfaceType) {
@ -58,8 +65,7 @@ class DartAccessorResolver
}
}
final rawViews = annotation.getField('views')!.toListValue()!;
for (final viewType in rawViews) {
for (final viewType in readList('views')) {
final dartType = viewType.toTypeValue();
if (dartType is! InterfaceType) {

View File

@ -112,7 +112,7 @@ void main() {
@DriftDatabase(tables: [Foo, DoesNotExist])
class Database {}
@DriftAccessor(tables: [DoesNotExist])
@DriftAccessor(views: [DoesNotExist])
class Accessor {}
''',
'a|lib/invalid_constraints.dart': '''
@ -298,7 +298,7 @@ void main() {
contains('Please make sure that all table classes exist.'),
)),
isDriftError(allOf(
contains('Could not read tables from @DriftAccessor annotation!'),
contains('Could not read views from @DriftAccessor annotation!'),
contains('Please make sure that all table classes exist.'),
)),
]),