Skip to content

Commit d98f3e3

Browse files
bkonyiflutter-zl
authored andcommitted
[ Widget Preview ] Fix crash when @Preview annotations appeared outside of lib/ (flutter#180768)
The widget preview scaffold requires that previews are defined within importable libraries. Since Dart does not support absolute paths for imports or relative imports outside of the project, it's not possible for the widget previewer to display previews defined outside of `lib/`. This change updates the preview detector to ignore libraries that don't have a package name (e.g., libraries under `test/`) and updates `packageName` properties to not allow for null to make it clear that package names are required for previews. Fixes flutter#178651
1 parent 4117f61 commit d98f3e3

11 files changed

Lines changed: 120 additions & 34 deletions

File tree

‎dev/integration_tests/widget_preview_scaffold/lib/src/widget_preview.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class WidgetPreview {
6262
///
6363
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
6464
/// will have the value 'foo'.
65-
final String? packageName;
65+
final String packageName;
6666

6767
/// A description to be displayed alongside the preview.
6868
///

‎dev/integration_tests/widget_preview_scaffold/lib/src/widget_preview_rendering.dart‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -881,11 +881,7 @@ class PreviewAssetBundle extends PlatformAssetBundle {
881881
///
882882
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
883883
/// will have the value 'foo'.
884-
///
885-
/// This should only be null if the preview is defined in a file that's not
886-
/// part of a Flutter library (e.g., is defined in a test).
887-
// TODO(bkonyi): verify what the behavior should be in this scenario.
888-
final String? packageName;
884+
final String packageName;
889885

890886
// Assets shipped via package dependencies have paths that start with
891887
// 'packages'.
@@ -903,8 +899,7 @@ class PreviewAssetBundle extends PlatformAssetBundle {
903899
if (key == 'AssetManifest.bin' ||
904900
key == 'AssetManifest.bin.json' ||
905901
key == 'FontManifest.json' ||
906-
key.startsWith(_kPackagesPrefix) ||
907-
packageName == null) {
902+
key.startsWith(_kPackagesPrefix)) {
908903
return super.load(key);
909904
}
910905
// Other assets are from the parent project. Map their keys to package

‎packages/flutter_tools/lib/src/widget_preview/dependency_graph.dart‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,10 @@ final class LibraryPreviewNode {
230230
void findPreviews({required ResolvedLibraryResult lib}) {
231231
// Iterate over the compilation unit's AST to find previews.
232232
final visitor = _PreviewVisitor(lib: lib.element);
233+
// Previews can only be defined under the lib/ directory.
234+
if (visitor.packageName == null) {
235+
return;
236+
}
233237
lib.units.forEach(visitor.findPreviewsInResolvedUnitResult);
234238
previews
235239
..clear()

‎packages/flutter_tools/lib/src/widget_preview/preview_detector.dart‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ class PreviewDetector {
3737
required this.onChangeDetected,
3838
required this.onPubspecChangeDetected,
3939
@visibleForTesting this.watcherBuilder = _defaultWatcherBuilder,
40+
@visibleForTesting this.onPackageConfigChangeDetected,
4041
}) : projectRoot = project.directory;
4142

4243
final Platform platform;
@@ -47,6 +48,8 @@ class PreviewDetector {
4748
final Logger logger;
4849
final void Function(PreviewDependencyGraph) onChangeDetected;
4950
final void Function(String path) onPubspecChangeDetected;
51+
@visibleForTesting
52+
final void Function(String path)? onPackageConfigChangeDetected;
5053
final WatcherBuilder watcherBuilder;
5154

5255
@visibleForTesting
@@ -64,20 +67,21 @@ class PreviewDetector {
6467
PreviewDependencyGraph get dependencyGraph => _dependencyGraph;
6568
final PreviewDependencyGraph _dependencyGraph = PreviewDependencyGraph();
6669

67-
late final collection = AnalysisContextCollection(
68-
includedPaths: <String>[projectRoot.absolute.path],
69-
resourceProvider: PhysicalResourceProvider.INSTANCE,
70+
@visibleForTesting
71+
AnalysisContextCollection get collection => _collection;
72+
late AnalysisContextCollection _collection;
73+
74+
late final String _packageConfigPath = fs.path.join(
75+
projectRoot.absolute.path,
76+
'.dart_tool',
77+
'package_config.json',
7078
);
7179

7280
/// Starts listening for changes to Dart sources under [projectRoot] and returns
7381
/// the initial [PreviewDependencyGraph] for the project.
7482
Future<PreviewDependencyGraph> initialize() {
7583
return mutex.runGuarded(() async {
76-
// Find the initial set of previews.
77-
await findPreviewFunctions(projectRoot);
78-
79-
// Determine which files have transitive dependencies with compile time errors.
80-
_propagateErrors();
84+
await _initializeAnalysisContextCollection();
8185

8286
final Watcher watcher = watcherBuilder(projectRoot.path);
8387
_fileWatcher = watcher.events.listen(
@@ -118,15 +122,38 @@ class PreviewDetector {
118122
await mutex.runGuarded(() async {
119123
await _fileWatcher?.cancel();
120124
_fileWatcher = null;
121-
await collection.dispose();
125+
await _collection.dispose();
122126
});
123127
}
124128

129+
Future<void> _initializeAnalysisContextCollection() async {
130+
_collection = AnalysisContextCollection(
131+
includedPaths: <String>[projectRoot.absolute.path],
132+
resourceProvider: PhysicalResourceProvider.INSTANCE,
133+
);
134+
135+
// Find the initial set of previews.
136+
await findPreviewFunctions(projectRoot);
137+
138+
// Determine which files have transitive dependencies with compile time errors.
139+
_propagateErrors();
140+
}
141+
125142
Future<void> _onFileSystemEvent(WatchEvent event) async {
126143
// Only process one FileSystemEntity at a time so we don't invalidate an AnalysisSession that's
127144
// in use when we call context.changeFile(...).
128145
await mutex.runGuarded(() async {
129146
final String eventPath = event.path;
147+
final File file = fs.file(eventPath);
148+
149+
// If the package_config.json for the project has been changed, we need to tear down the
150+
// analysis context collection and recreate it to pick up the changes.
151+
if (file.absolute.path == _packageConfigPath) {
152+
await _collection.dispose();
153+
await _initializeAnalysisContextCollection();
154+
onPackageConfigChangeDetected?.call(event.path);
155+
return;
156+
}
130157
// Ignore any files under .dart_tool or ephemeral directories created by
131158
// the tool (e.g., build/, plugin directories, etc.).
132159
if (eventPath.doesContainDartTool ||
@@ -147,7 +174,7 @@ class PreviewDetector {
147174

148175
AnalysisContext context;
149176
try {
150-
context = collection.contextFor(eventPath);
177+
context = _collection.contextFor(eventPath);
151178
} on StateError {
152179
// The modified file isn't part of the analysis context and is safe to
153180
// ignore.
@@ -168,7 +195,6 @@ class PreviewDetector {
168195
// extension which may be worth using here.
169196

170197
// We need to notify the analyzer that this file has changed so it can reanalyze the file.
171-
final File file = fs.file(eventPath);
172198
context.changeFile(file.path);
173199
final List<String> potentiallyAffectedFiles;
174200
try {
@@ -243,7 +269,7 @@ class PreviewDetector {
243269
final PreviewDependencyGraph updatedPreviews = PreviewDependencyGraph();
244270

245271
logger.printStatus('Finding previews in ${entity.path}...');
246-
for (final AnalysisContext context in collection.contexts) {
272+
for (final AnalysisContext context in _collection.contexts) {
247273
for (final String filePath in context.contextRoot.analyzedFiles()) {
248274
logger.printTrace('Checking file: $filePath');
249275
if (!filePath.isDartFile || !filePath.startsWith(entity.path)) {

‎packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview.dart.tmpl‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ class WidgetPreview {
6262
///
6363
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
6464
/// will have the value 'foo'.
65-
final String? packageName;
65+
final String packageName;
6666

6767
/// A description to be displayed alongside the preview.
6868
///

‎packages/flutter_tools/templates/widget_preview_scaffold/lib/src/widget_preview_rendering.dart.tmpl‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -881,11 +881,7 @@ class PreviewAssetBundle extends PlatformAssetBundle {
881881
///
882882
/// For example, if a preview is defined in 'package:foo/src/bar.dart', this
883883
/// will have the value 'foo'.
884-
///
885-
/// This should only be null if the preview is defined in a file that's not
886-
/// part of a Flutter library (e.g., is defined in a test).
887-
// TODO(bkonyi): verify what the behavior should be in this scenario.
888-
final String? packageName;
884+
final String packageName;
889885
890886
// Assets shipped via package dependencies have paths that start with
891887
// 'packages'.
@@ -903,8 +899,7 @@ class PreviewAssetBundle extends PlatformAssetBundle {
903899
if (key == 'AssetManifest.bin' ||
904900
key == 'AssetManifest.bin.json' ||
905901
key == 'FontManifest.json' ||
906-
key.startsWith(_kPackagesPrefix) ||
907-
packageName == null) {
902+
key.startsWith(_kPackagesPrefix)) {
908903
return super.load(key);
909904
}
910905
// Other assets are from the parent project. Map their keys to package

‎packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_code_generator_test.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,7 @@ List<_i1.WidgetPreview> previews() => [];
409409
testUsingContext(
410410
'correctly generates ${PreviewCodeGenerator.getGeneratedDtdConnectionInfoFilePath(fs)}',
411411
() async {
412+
await previewDetector.initialize();
412413
// Check that the generated preview file doesn't exist yet.
413414
final File generatedDtdConnectionInfoFile = project.widgetPreviewScaffold.childFile(
414415
PreviewCodeGenerator.getGeneratedDtdConnectionInfoFilePath(fs),

‎packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_detector/preview_detector_test.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,33 @@ void main() {
177177
expect(nodesWithPreviews.keys, unorderedMatches(project.librariesWithPreviews));
178178
expectNPreviewReloadTimingEvents(previewDetector, 2);
179179
});
180+
181+
testPreviewDetector('does not detect previews defined in tests', (
182+
PreviewDetector previewDetector,
183+
) async {
184+
project = await createProject(
185+
projectRoot: previewDetector.projectRoot,
186+
pathsWithPreviews: <String>[],
187+
pathsWithoutPreviews: <String>[],
188+
);
189+
// The initial mapping should be empty as there's no files containing previews.
190+
const expectedInitialMapping = <PreviewPath, LibraryPreviewNode>{};
191+
192+
final PreviewDependencyGraph mapping = await previewDetector.initialize();
193+
expect(mapping.nodesWithPreviews, expectedInitialMapping);
194+
expectNPreviewReloadTimingEvents(previewDetector, 0);
195+
196+
// Add a file containing previews under the test directory. Previews outside of lib/ are
197+
// not valid.
198+
await waitForNChangesDetected(
199+
n: 1,
200+
changeOperation: () => project.addPreviewContainingTestFile(path: 'foo.dart'),
201+
);
202+
final PreviewDependencyGraph nodesWithPreviews =
203+
previewDetector.dependencyGraph.nodesWithPreviews;
204+
expect(nodesWithPreviews, isEmpty);
205+
expectNPreviewReloadTimingEvents(previewDetector, 1);
206+
});
180207
}
181208

182209
testPreviewDetector('can detect changes in the pubspec.yaml', (

‎packages/flutter_tools/test/commands.shard/hermetic/widget_preview/preview_detector/preview_detector_workspace_test.dart‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,20 @@ Widget foo() => Text('Hello world!');
102102
final PreviewDependencyGraph initialPreviews = await previewDetector.initialize();
103103
expect(initialPreviews.nodesWithPreviews.length, 2);
104104

105+
late WidgetPreviewProject bazProject;
106+
await waitForPackageConfigChangeDetected(
107+
changeOperation: () async =>
108+
bazProject = await workspace.createWorkspaceProject(name: 'baz'),
109+
);
110+
105111
// Add a new project to the workspace with single preview and verify it's detected.
106112
await waitForChangeDetected(
107113
onChangeDetected: (PreviewDependencyGraph updated) {
108114
// The new preview in baz.dart should be included in the preview mapping.
109115
expect(updated.nodesWithPreviews.length, 3);
110116
},
111-
changeOperation: () async =>
112-
(await workspace.createWorkspaceProject(name: 'baz'))
113-
..writeFile((path: 'baz.dart', source: simplePreviewSource)),
117+
changeOperation: () =>
118+
bazProject.writeFile((path: 'baz.dart', source: simplePreviewSource)),
114119
);
115120
});
116121

‎packages/flutter_tools/test/commands.shard/hermetic/widget_preview/utils/preview_detector_test_utils.dart‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ var _stateInitialized = false;
2828
// Global state that must be cleaned up by `tearDown` in initializeTestPreviewDetectorState.
2929
void Function(PreviewDependencyGraph)? _onChangeDetectedImpl;
3030
void Function(String path)? _onPubspecChangeDetected;
31+
void Function(String path)? _onPackageConfigChangeDetected;
3132
Directory? _projectRoot;
3233

3334
late FileSystem _fs;
@@ -43,6 +44,7 @@ void initializeTestPreviewDetectorState() {
4344
tearDown(() {
4445
_onChangeDetectedImpl = null;
4546
_onPubspecChangeDetected = null;
47+
_onPackageConfigChangeDetected = null;
4648
_projectRoot?.deleteSync(recursive: true);
4749
_projectRoot = null;
4850
});
@@ -96,6 +98,7 @@ PreviewDetector createTestPreviewDetector() {
9698
fs: _fs,
9799
onChangeDetected: _onChangeDetectedRoot,
98100
onPubspecChangeDetected: _onPubspecChangeDetectedRoot,
101+
onPackageConfigChangeDetected: _onPackageConfigChangeDetectedRoot,
99102
);
100103
}
101104

@@ -119,6 +122,10 @@ void _onPubspecChangeDetectedRoot(String path) {
119122
_onPubspecChangeDetected?.call(path);
120123
}
121124

125+
void _onPackageConfigChangeDetectedRoot(String path) {
126+
_onPackageConfigChangeDetected?.call(path);
127+
}
128+
122129
/// Test the files included in [filesWithErrors] contain errors after executing [changeOperation].
123130
Future<void> expectHasErrors({
124131
required WidgetPreviewProject project,
@@ -161,6 +168,19 @@ Future<String> waitForPubspecChangeDetected({required void Function() changeOper
161168
return completer.future;
162169
}
163170

171+
/// Waits for a package_config.json changed event to be detected after executing [changeOperation].
172+
Future<String> waitForPackageConfigChangeDetected({required void Function() changeOperation}) {
173+
final completer = Completer<String>();
174+
_onPackageConfigChangeDetected = (String path) {
175+
if (completer.isCompleted) {
176+
return;
177+
}
178+
completer.complete(path);
179+
};
180+
changeOperation();
181+
return completer.future;
182+
}
183+
164184
/// Waits for a change detected event after executing [changeOperation].
165185
///
166186
/// Invokes [onChangeDetected] when a change is detected before the returned future is completed.

0 commit comments

Comments
 (0)