Skip to content

Commit

Permalink
Include directives in LibraryReader.allElements (#663)
Browse files Browse the repository at this point in the history
Closes #662

Allows targeting annotated imports, exports, or part directives with
`GeneratorForAnnotation`.

A pattern established by Mockito is to annotate the import of the file
that will be generated.
  • Loading branch information
natebosch authored May 4, 2023
1 parent 995cd6a commit c53727e
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
2 changes: 2 additions & 0 deletions source_gen/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
`build_extensions: { '.dart': ['.stub.dart', '.web.dart', '.vm.dart'] }`
* Avoid throwing when a type without a backing class is checked with
`TypeChecker`.
* Include imports, exports, and part directives in `LibraryReader.allElements`.
This allows `GeneratorForAnnotation` to target annotated directives.

## 1.2.7

Expand Down
8 changes: 7 additions & 1 deletion source_gen/lib/src/library.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,13 @@ class LibraryReader {
}

/// All of the declarations in this library.
Iterable<Element> get allElements => [element, ...element.topLevelElements];
Iterable<Element> get allElements => [
element,
...element.topLevelElements,
...element.libraryImports,
...element.libraryExports,
...element.parts,
];

/// All of the declarations in this library annotated with [checker].
Iterable<AnnotatedElement> annotatedWith(
Expand Down
40 changes: 40 additions & 0 deletions source_gen/test/generator_for_annotation_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,46 @@ void main() {
// **************************************************************************
// foo
'''
},
);
});

test('applies to annotated directives', () async {
final builder = LibraryBuilder(
_StubGenerator<Deprecated>(
'Deprecated',
(element) => '// ${element.runtimeType}',
),
);
await testBuilder(
builder,
{
'a|lib/imported.dart': '',
'a|lib/part.dart': 'part of \'file.dart\';',
'a|lib/file.dart': '''
library;
@deprecated
import 'imported.dart';
@deprecated
export 'imported.dart';
@deprecated
part 'part.dart';
'''
},
outputs: {
'a|lib/file.g.dart': '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// Generator: Deprecated
// **************************************************************************
// LibraryImportElementImpl
// LibraryExportElementImpl
// PartElementImpl
'''
},
);
Expand Down

0 comments on commit c53727e

Please sign in to comment.