Skip to content

Commit c53727e

Browse files
authored
Include directives in LibraryReader.allElements (#663)
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.
1 parent 995cd6a commit c53727e

File tree

3 files changed

+49
-1
lines changed

3 files changed

+49
-1
lines changed

source_gen/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
`build_extensions: { '.dart': ['.stub.dart', '.web.dart', '.vm.dart'] }`
66
* Avoid throwing when a type without a backing class is checked with
77
`TypeChecker`.
8+
* Include imports, exports, and part directives in `LibraryReader.allElements`.
9+
This allows `GeneratorForAnnotation` to target annotated directives.
810

911
## 1.2.7
1012

source_gen/lib/src/library.dart

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ class LibraryReader {
3434
}
3535

3636
/// All of the declarations in this library.
37-
Iterable<Element> get allElements => [element, ...element.topLevelElements];
37+
Iterable<Element> get allElements => [
38+
element,
39+
...element.topLevelElements,
40+
...element.libraryImports,
41+
...element.libraryExports,
42+
...element.parts,
43+
];
3844

3945
/// All of the declarations in this library annotated with [checker].
4046
Iterable<AnnotatedElement> annotatedWith(

source_gen/test/generator_for_annotation_test.dart

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,46 @@ void main() {
134134
// **************************************************************************
135135
136136
// foo
137+
'''
138+
},
139+
);
140+
});
141+
142+
test('applies to annotated directives', () async {
143+
final builder = LibraryBuilder(
144+
_StubGenerator<Deprecated>(
145+
'Deprecated',
146+
(element) => '// ${element.runtimeType}',
147+
),
148+
);
149+
await testBuilder(
150+
builder,
151+
{
152+
'a|lib/imported.dart': '',
153+
'a|lib/part.dart': 'part of \'file.dart\';',
154+
'a|lib/file.dart': '''
155+
library;
156+
@deprecated
157+
import 'imported.dart';
158+
@deprecated
159+
export 'imported.dart';
160+
@deprecated
161+
part 'part.dart';
162+
'''
163+
},
164+
outputs: {
165+
'a|lib/file.g.dart': '''
166+
// GENERATED CODE - DO NOT MODIFY BY HAND
167+
168+
// **************************************************************************
169+
// Generator: Deprecated
170+
// **************************************************************************
171+
172+
// LibraryImportElementImpl
173+
174+
// LibraryExportElementImpl
175+
176+
// PartElementImpl
137177
'''
138178
},
139179
);

0 commit comments

Comments
 (0)