Skip to content

Commit 7280083

Browse files
[beta] [flutter_tools] Fix StateError in testCompilerBuildNativeAssets when package root does not match projectUri (#194958)
This pull request is created by [automatic cherry pick workflow](https://github.com/flutter/flutter/blob/main/docs/releases/Flutter-Cherrypick-Process.md#automatically-creates-a-cherry-pick-request) Please fill in the form below, and a flutter domain expert will evaluate this cherry pick request. ### Issue Link: #192933 ### Impact Description: Fixes a `StateError (Bad state: No element)` crash in `testCompilerBuildNativeAssets` when running `flutter test` in directories where the package root URI does not strictly match `projectUri` in `package_config.json` (such as in pub workspaces, monorepos, symlinked project directories, or when ancestor `package_config.json` files are used). This crash blocks affected users from running `flutter test`. ### Changelog Description: [flutter/192933] When running `flutter test` in pub workspaces, monorepos, or symlinked directories, fix a StateError crash during native assets compilation by falling back to appName matching. ### Workaround: Run `flutter test` from the exact directory matching the package root or pass `--no-native-assets` when native assets are not required. ### Risk: ### Test Coverage: Are you confident that your fix is well-tested by automated tests? ### Validation Steps: Run `flutter test` in a project with a symlinked path or inside a pub workspace member package and verify that `testCompilerBuildNativeAssets` executes cleanly without throwing `StateError (Bad state: No element)`.
1 parent d89e7f4 commit 7280083

2 files changed

Lines changed: 444 additions & 13 deletions

File tree

‎packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart‎

Lines changed: 106 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,10 @@
55
// Logic for native assets shared between all host OSes.
66

77
import 'package:code_assets/code_assets.dart' show OS;
8+
import 'package:meta/meta.dart';
89
import 'package:package_config/package_config_types.dart';
910

11+
import '../../../base/file_system.dart';
1012
import '../../../base/platform.dart';
1113
import '../../../build_info.dart';
1214
import '../../../globals.dart' as globals;
@@ -15,6 +17,11 @@ import '../../../project.dart';
1517
import '../dart_hook_result.dart';
1618
import '../native_assets.dart';
1719

20+
const _fileScheme = 'file';
21+
const _nativeAssetsJsonFileName = 'native_assets.json';
22+
const _pubspecYamlFileName = 'pubspec.yaml';
23+
24+
/// Builds native assets for `flutter test` targets on the host platform.
1825
class TestCompilerNativeAssetsBuilderImpl implements TestCompilerNativeAssetsBuilder {
1926
const TestCompilerNativeAssetsBuilderImpl();
2027

@@ -33,28 +40,55 @@ class TestCompilerNativeAssetsBuilderImpl implements TestCompilerNativeAssetsBui
3340
}
3441
}
3542

43+
/// Builds native assets for `flutter test` execution using [buildInfo].
44+
///
45+
/// Resolves the target package name for the current project and executes build
46+
/// and install hooks for the host test platform ([TargetPlatform.tester]),
47+
/// writing the generated manifest to `build/native_assets/<os>/native_assets.json`.
48+
///
49+
/// Returns the [TestCompilerNativeAssetsBuildResult] containing the [Uri] to the
50+
/// generated `native_assets.json` file and hook output, or `null` fields if
51+
/// native assets are disabled, unsupported on the host OS, or no package can
52+
/// be resolved.
3653
Future<TestCompilerNativeAssetsBuildResult> testCompilerBuildNativeAssets(
3754
BuildInfo buildInfo,
3855
) async {
39-
if (!buildInfo.buildNativeAssets) {
56+
final BuildInfo(
57+
:bool buildNativeAssets,
58+
:BuildMode mode,
59+
:PackageConfig packageConfig,
60+
:String packageConfigPath,
61+
) = buildInfo;
62+
if (!buildNativeAssets) {
63+
return (nativeAssetsManifest: null, flutterHookResult: null);
64+
}
65+
final FlutterProject project = FlutterProject.current();
66+
final Uri projectUri = project.directory.uri;
67+
final String? runPackageName = findRunPackageName(
68+
fileSystem: project.directory.fileSystem,
69+
manifestAppName: project.manifest.appName,
70+
packageConfig: packageConfig,
71+
projectUri: projectUri,
72+
);
73+
if (runPackageName == null) {
74+
globals.logger.printWarning(
75+
'Could not determine run package name for native assets testing '
76+
'(projectUri: $projectUri, packageConfigPath: $packageConfigPath).',
77+
);
4078
return (nativeAssetsManifest: null, flutterHookResult: null);
4179
}
42-
final Uri projectUri = FlutterProject.current().directory.uri;
43-
final String runPackageName = buildInfo.packageConfig.packages
44-
.firstWhere((Package p) => p.root == projectUri)
45-
.name;
46-
final String pubspecPath = Uri.file(buildInfo.packageConfigPath)
47-
.resolve('../pubspec.yaml')
80+
final String pubspecPath = Uri.file(packageConfigPath)
81+
.resolve('../$_pubspecYamlFileName')
4882
.toFilePath();
4983
final FlutterNativeAssetsBuildRunner buildRunner = FlutterNativeAssetsBuildRunnerImpl(
50-
buildInfo.packageConfigPath,
51-
buildInfo.packageConfig,
84+
packageConfigPath,
85+
packageConfig,
5286
globals.fs,
5387
globals.logger,
5488
globals.platform,
5589
runPackageName,
56-
includeDevDependencies: true,
5790
pubspecPath,
91+
includeDevDependencies: true,
5892
);
5993

6094
if (!globals.platform.isMacOS && !globals.platform.isLinux && !globals.platform.isWindows) {
@@ -74,9 +108,9 @@ Future<TestCompilerNativeAssetsBuildResult> testCompilerBuildNativeAssets(
74108
final String buildDir = getBuildDirectory();
75109
final String osName = targetOS.name;
76110
final Uri buildUri = projectUri.resolve('$buildDir/native_assets/$osName/');
77-
final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.json');
111+
final Uri nativeAssetsFileUri = buildUri.resolve(_nativeAssetsJsonFileName);
78112

79-
final environmentDefines = <String, String>{kBuildMode: buildInfo.mode.cliName};
113+
final environmentDefines = <String, String>{kBuildMode: mode.cliName};
80114

81115
// First perform the dart build.
82116
final DartHooksResult dartHookResult = await runFlutterSpecificHooks(
@@ -101,7 +135,7 @@ Future<TestCompilerNativeAssetsBuildResult> testCompilerBuildNativeAssets(
101135
projectUri: projectUri,
102136
fileSystem: globals.fs,
103137
nativeAssetsFileUri: nativeAssetsFileUri,
104-
targetUri: projectUri.resolve('${getBuildDirectory()}/native_assets/$osName/'),
138+
targetUri: buildUri,
105139
);
106140
assert(globals.fs.file(nativeAssetsFileUri).existsSync());
107141

@@ -110,3 +144,62 @@ Future<TestCompilerNativeAssetsBuildResult> testCompilerBuildNativeAssets(
110144
flutterHookResult: dartHookResult.asFlutterResult,
111145
);
112146
}
147+
148+
/// Resolves the target package name for native assets builds using the following
149+
/// fallback order:
150+
///
151+
/// 1. A package in [packageConfig] whose `root` URI directly matches [projectUri].
152+
/// 2. A package in [packageConfig] whose canonicalized `root` path matches the
153+
/// canonicalized path of [projectUri] (handling symlinks and trailing slashes).
154+
/// 3. [manifestAppName] if it is non-empty and exists in [packageConfig].
155+
/// 4. `null` if no package name can be determined.
156+
@visibleForTesting
157+
String? findRunPackageName({
158+
required FileSystem fileSystem,
159+
required String manifestAppName,
160+
required PackageConfig packageConfig,
161+
required Uri projectUri,
162+
}) {
163+
// 1. Direct match on package root URI.
164+
final Package? directMatch = packageConfig.packages
165+
.where((Package p) => p.root == projectUri)
166+
.firstOrNull;
167+
if (directMatch != null) {
168+
return directMatch.name;
169+
}
170+
171+
// 2. Canonicalized path match (handles symlinks, trailing slashes, etc.).
172+
if (projectUri.isScheme(_fileScheme) && packageConfig.packages.isNotEmpty) {
173+
final String canonicalProjectDir = _canonicalizeUriPath(fileSystem, projectUri);
174+
final Package? pathMatch = packageConfig.packages.where((Package p) {
175+
if (!p.root.isScheme(_fileScheme)) {
176+
return false;
177+
}
178+
return _canonicalizeUriPath(fileSystem, p.root) == canonicalProjectDir;
179+
}).firstOrNull;
180+
if (pathMatch != null) {
181+
return pathMatch.name;
182+
}
183+
}
184+
185+
// 3. Fallback to the project manifest app name if it exists in packageConfig.
186+
if (manifestAppName.isNotEmpty && packageConfig[manifestAppName] != null) {
187+
return manifestAppName;
188+
}
189+
190+
return null;
191+
}
192+
193+
String _canonicalizeUriPath(FileSystem fileSystem, Uri uri) {
194+
final String path = fileSystem.path.fromUri(uri);
195+
final Directory directory = fileSystem.directory(path);
196+
var resolvedPath = path;
197+
if (directory.existsSync()) {
198+
try {
199+
resolvedPath = directory.resolveSymbolicLinksSync();
200+
} on FileSystemException {
201+
// Fall back to the unresolved path if symlink resolution fails.
202+
}
203+
}
204+
return fileSystem.path.canonicalize(resolvedPath);
205+
}

0 commit comments

Comments
 (0)