Skip to content

Commit 53643c2

Browse files
authored
[flutter_tools] Resolve workspace root when running widget preview from member package (flutter#190952)
When `flutter widget-preview start` is run from a member package in a pub workspace, redirect `getRootProject()` to the workspace root `FlutterProject`. This ensures that the widget preview scaffold is generated at the workspace root and has dependency overrides for all member packages in the workspace. Fixes flutter#190692
1 parent bb5b1dc commit 53643c2

4 files changed

Lines changed: 226 additions & 10 deletions

File tree

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,13 @@ abstract base class WidgetPreviewSubCommandBase extends FlutterCommand {
114114
} else {
115115
projectDir = fs.currentDirectory;
116116
}
117-
return validateFlutterProjectForPreview(projectDir);
117+
final FlutterProject project = validateFlutterProjectForPreview(projectDir);
118+
final FlutterProject? workspaceRoot = project.workspaceRoot;
119+
if (workspaceRoot != null) {
120+
logger.printTrace('Found workspace root at ${workspaceRoot.directory.path}');
121+
return workspaceRoot;
122+
}
123+
return project;
118124
}
119125

120126
FlutterProject validateFlutterProjectForPreview(Directory directory) {

‎packages/flutter_tools/lib/src/project.dart‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,62 @@ class FlutterProject {
9595
_setManifest(manifest);
9696
}
9797

98+
FlutterProject? _workspaceRoot;
99+
bool _searchedForWorkspaceRoot = false;
100+
101+
/// Returns the workspace root project if this project is a member of a workspace.
102+
///
103+
/// Returns null if this project is not part of a workspace or is itself the workspace root.
104+
FlutterProject? get workspaceRoot {
105+
if (_searchedForWorkspaceRoot) {
106+
return _workspaceRoot;
107+
}
108+
_searchedForWorkspaceRoot = true;
109+
_workspaceRoot = _findWorkspaceRoot();
110+
return _workspaceRoot;
111+
}
112+
113+
FlutterProject? _findWorkspaceRoot() {
114+
final FileSystem fileSystem = directory.fileSystem;
115+
final String normalizedPath = fileSystem.path.normalize(directory.absolute.path);
116+
Directory candidate = fileSystem.directory(normalizedPath);
117+
118+
while (true) {
119+
final Directory parent = candidate.parent;
120+
if (fileSystem.path.equals(parent.path, candidate.path)) {
121+
break;
122+
}
123+
candidate = parent;
124+
final File pubspec = candidate.childFile('pubspec.yaml');
125+
if (!pubspec.existsSync()) {
126+
continue;
127+
}
128+
try {
129+
final FlutterManifest manifest = FlutterProject._readManifest(
130+
pubspec.path,
131+
logger: globals.logger,
132+
fileSystem: fileSystem,
133+
);
134+
if (manifest.workspace.isNotEmpty) {
135+
final String relativePath = fileSystem.path.relative(
136+
normalizedPath,
137+
from: candidate.path,
138+
);
139+
final bool isMember = manifest.workspace.any((String entry) {
140+
final glob = Glob(entry, context: fileSystem.path);
141+
return glob.matches(relativePath);
142+
});
143+
if (isMember) {
144+
return FlutterProject.fromDirectory(candidate);
145+
}
146+
}
147+
} on Exception catch (_) {
148+
// Ignore manifest reading errors.
149+
}
150+
}
151+
return null;
152+
}
153+
98154
/// Returns a [FlutterProject] view of the given directory or a ToolExit error,
99155
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
100156
static FlutterProject fromDirectory(Directory directory) =>
@@ -142,17 +198,23 @@ class FlutterProject {
142198

143199
void _setManifest(FlutterManifest manifest) {
144200
_manifest = manifest;
201+
_searchedForWorkspaceRoot = false;
202+
_workspaceRoot = null;
145203

146204
// Update the workspace projects based on the new manifest.
147205
_workspaceProjects = <FlutterProject>[];
148206
for (final String entry in manifest.workspace) {
149-
final glob = Glob(entry);
207+
final glob = Glob(entry, context: directory.fileSystem.path);
150208
for (final Directory globResult
151209
in glob
152210
.listFileSystemSync(directory.fileSystem, root: directory.path)
153211
.whereType<Directory>()) {
154212
if (globResult.childFile('pubspec.yaml').existsSync()) {
155-
_workspaceProjects.add(FlutterProject.fromDirectory(globResult));
213+
try {
214+
_workspaceProjects.add(FlutterProject.fromDirectory(globResult));
215+
} on Exception catch (_) {
216+
// Ignore child projects with invalid manifests.
217+
}
156218
}
157219
}
158220
}

‎packages/flutter_tools/test/commands.shard/permeable/widget_preview/widget_preview_test.dart‎

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -284,13 +284,7 @@ void main() {
284284

285285
Future<void> cleanWidgetPreview({required Directory rootProject}) async {
286286
await runWidgetPreviewCommand(<String>['clean', rootProject.path]);
287-
expect(
288-
fs
289-
.directory(rootProject)
290-
.childDirectory('.dart_tool')
291-
.childDirectory('widget_preview_scaffold'),
292-
isNot(exists),
293-
);
287+
expect(fs.directory(rootProject).childDirectory('.widget_preview'), isNot(exists));
294288
}
295289

296290
group('flutter widget-preview', () {
@@ -389,6 +383,62 @@ void main() {
389383
);
390384
});
391385

386+
group('workspaces', () {
387+
testUsingContext(
388+
'starts from workspace root when run from member package',
389+
() async {
390+
final File workspacePubspec = tempDir.childFile('pubspec.yaml');
391+
workspacePubspec.writeAsStringSync('''
392+
name: my_workspace
393+
environment:
394+
sdk: '>=3.0.0 <4.0.0'
395+
workspace:
396+
- my_app
397+
''');
398+
399+
final String memberProjectPath = await createProject(
400+
tempDir,
401+
name: 'my_app',
402+
arguments: <String>['--pub'],
403+
);
404+
final Directory memberProjectDir = fs.directory(memberProjectPath);
405+
406+
final File memberPubspec = memberProjectDir.childFile('pubspec.yaml');
407+
final String memberPubspecContent = memberPubspec.readAsStringSync();
408+
memberPubspec.writeAsStringSync('''
409+
$memberPubspecContent
410+
resolution: workspace
411+
''');
412+
413+
fs.currentDirectory = memberProjectDir;
414+
415+
await startWidgetPreview(rootProject: null);
416+
final Directory workspaceScaffoldDir = tempDir.childDirectory('.widget_preview');
417+
final Directory memberScaffoldDir = memberProjectDir.childDirectory('.widget_preview');
418+
419+
expect(workspaceScaffoldDir, exists);
420+
expect(memberScaffoldDir, isNot(exists));
421+
422+
await cleanWidgetPreview(rootProject: tempDir);
423+
},
424+
overrides: <Type, Generator>{
425+
Analytics: () => fakeAnalytics,
426+
DeviceManager: () => fakeDeviceManager,
427+
FileSystem: () => fs,
428+
ProcessManager: () => loggingProcessManager,
429+
FeatureFlags: () => TestFeatureFlags(isWebEnabled: true),
430+
Pub: () => Pub.test(
431+
fileSystem: fs,
432+
logger: logger,
433+
processManager: loggingProcessManager,
434+
botDetector: botDetector,
435+
platform: platform,
436+
stdio: mockStdio,
437+
),
438+
},
439+
);
440+
});
441+
392442
testUsingContext(
393443
'start succeeds when no .dart_tool/ directory exists',
394444
() async {

‎packages/flutter_tools/test/general.shard/project_test.dart‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2046,6 +2046,104 @@ resolution: workspace
20462046
<String>['child1', 'child2'],
20472047
);
20482048
});
2049+
2050+
_testInMemory('workspaceRoot returns root project for member projects', () async {
2051+
final Directory directory = globals.fs.directory('myproject');
2052+
directory.childFile('pubspec.yaml')
2053+
..createSync(recursive: true)
2054+
..writeAsStringSync('''
2055+
name: parent
2056+
flutter:
2057+
workspace:
2058+
- pkgs/*
2059+
''');
2060+
final Directory child1Dir = directory.childDirectory('pkgs').childDirectory('child1');
2061+
child1Dir.childFile('pubspec.yaml')
2062+
..createSync(recursive: true)
2063+
..writeAsStringSync('''
2064+
name: child1
2065+
flutter:
2066+
resolution: workspace
2067+
''');
2068+
2069+
final FlutterProject parentProject = FlutterProject.fromDirectory(directory);
2070+
final FlutterProject childProject = FlutterProject.fromDirectory(child1Dir);
2071+
2072+
expect(
2073+
globals.fs.path.canonicalize(childProject.workspaceRoot!.directory.path),
2074+
globals.fs.path.canonicalize(parentProject.directory.path),
2075+
);
2076+
expect(parentProject.workspaceRoot, null);
2077+
});
2078+
2079+
_testInMemory('workspaceRoot works with relative paths', () async {
2080+
final Directory directory = globals.fs.directory('myproject')..createSync(recursive: true);
2081+
directory.childFile('pubspec.yaml').writeAsStringSync('''
2082+
name: parent
2083+
flutter:
2084+
workspace:
2085+
- child1
2086+
''');
2087+
final Directory child1Dir = directory.childDirectory('child1')..createSync(recursive: true);
2088+
child1Dir.childFile('pubspec.yaml').writeAsStringSync('''
2089+
name: child1
2090+
flutter:
2091+
resolution: workspace
2092+
''');
2093+
2094+
final Directory originalCwd = globals.fs.currentDirectory;
2095+
try {
2096+
globals.fs.currentDirectory = directory;
2097+
final FlutterProject childProject = FlutterProject.fromDirectory(
2098+
globals.fs.directory('child1'),
2099+
);
2100+
expect(
2101+
globals.fs.path.canonicalize(childProject.workspaceRoot!.directory.path),
2102+
globals.fs.path.canonicalize(globals.fs.currentDirectory.path),
2103+
);
2104+
} finally {
2105+
globals.fs.currentDirectory = originalCwd;
2106+
}
2107+
});
2108+
2109+
_testInMemory(
2110+
'workspaceRoot is resilient to malformed sibling packages in workspace',
2111+
() async {
2112+
final Directory directory = globals.fs.directory('myproject');
2113+
directory.childFile('pubspec.yaml')
2114+
..createSync(recursive: true)
2115+
..writeAsStringSync('''
2116+
name: parent
2117+
flutter:
2118+
workspace:
2119+
- pkgs/*
2120+
''');
2121+
final Directory validChildDir = directory
2122+
.childDirectory('pkgs')
2123+
.childDirectory('valid_child');
2124+
validChildDir.childFile('pubspec.yaml')
2125+
..createSync(recursive: true)
2126+
..writeAsStringSync('''
2127+
name: valid_child
2128+
flutter:
2129+
resolution: workspace
2130+
''');
2131+
final Directory brokenChildDir = directory
2132+
.childDirectory('pkgs')
2133+
.childDirectory('broken_child');
2134+
brokenChildDir.childFile('pubspec.yaml')
2135+
..createSync(recursive: true)
2136+
..writeAsStringSync('invalid: yaml: [broken');
2137+
2138+
final FlutterProject parentProject = FlutterProject.fromDirectory(directory);
2139+
final FlutterProject childProject = FlutterProject.fromDirectory(validChildDir);
2140+
2141+
expect(
2142+
globals.fs.path.canonicalize(childProject.workspaceRoot!.directory.path),
2143+
globals.fs.path.canonicalize(parentProject.directory.path),
2144+
);
2145+
},
2146+
);
20492147
});
20502148
});
20512149

0 commit comments

Comments
 (0)