Skip to content

Commit b3804a3

Browse files
authored
[stable] [flutter_tools] Fix StateError in testCompilerBuildNativeAssets when package root does not match projectUri (#194959)
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 was observed in Flutter 3.47.3 crash telemetry and 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)`. ### Conflicts Resolved: - `packages/flutter_tools/lib/src/isolated/native_assets/test/native_assets.dart`: Adapted `testCompilerBuildNativeAssets` to maintain the `Future<Uri?>` return type and constructor signature present on `flutter-3.47-candidate.0`, returning `null` on failure and `nativeAssetsFileUri` on success. - `packages/flutter_tools/test/general.shard/isolated/native_assets_test.dart`: Updated regression tests to expect `Uri?` rather than the `TestCompilerNativeAssetsBuildResult` record type introduced in later master commits.
1 parent cbf63ce commit b3804a3

2 files changed

Lines changed: 441 additions & 13 deletions

File tree

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

Lines changed: 105 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

@@ -28,25 +35,51 @@ class TestCompilerNativeAssetsBuilderImpl implements TestCompilerNativeAssetsBui
2835
}
2936
}
3037

38+
/// Builds native assets for `flutter test` execution using [buildInfo].
39+
///
40+
/// Resolves the target package name for the current project and executes build
41+
/// and install hooks for the host test platform ([TargetPlatform.tester]),
42+
/// writing the generated manifest to `build/native_assets/<os>/native_assets.json`.
43+
///
44+
/// Returns the [Uri] to the generated `native_assets.json` file, or `null` if
45+
/// native assets are disabled, unsupported on the host OS, or no package can
46+
/// be resolved.
3147
Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
32-
if (!buildInfo.buildNativeAssets) {
48+
final BuildInfo(
49+
:bool buildNativeAssets,
50+
:BuildMode mode,
51+
:PackageConfig packageConfig,
52+
:String packageConfigPath,
53+
) = buildInfo;
54+
if (!buildNativeAssets) {
55+
return null;
56+
}
57+
final FlutterProject project = FlutterProject.current();
58+
final Uri projectUri = project.directory.uri;
59+
final String? runPackageName = findRunPackageName(
60+
fileSystem: project.directory.fileSystem,
61+
manifestAppName: project.manifest.appName,
62+
packageConfig: packageConfig,
63+
projectUri: projectUri,
64+
);
65+
if (runPackageName == null) {
66+
globals.logger.printWarning(
67+
'Could not determine run package name for native assets testing '
68+
'(projectUri: $projectUri, packageConfigPath: $packageConfigPath).',
69+
);
3370
return null;
3471
}
35-
final Uri projectUri = FlutterProject.current().directory.uri;
36-
final String runPackageName = buildInfo.packageConfig.packages
37-
.firstWhere((Package p) => p.root == projectUri)
38-
.name;
3972
final String pubspecPath = Uri.file(
40-
buildInfo.packageConfigPath,
41-
).resolve('../pubspec.yaml').toFilePath();
73+
packageConfigPath,
74+
).resolve('../$_pubspecYamlFileName').toFilePath();
4275
final FlutterNativeAssetsBuildRunner buildRunner = FlutterNativeAssetsBuildRunnerImpl(
43-
buildInfo.packageConfigPath,
44-
buildInfo.packageConfig,
76+
packageConfigPath,
77+
packageConfig,
4578
globals.fs,
4679
globals.logger,
4780
runPackageName,
48-
includeDevDependencies: true,
4981
pubspecPath,
82+
includeDevDependencies: true,
5083
);
5184

5285
if (!globals.platform.isMacOS && !globals.platform.isLinux && !globals.platform.isWindows) {
@@ -66,9 +99,9 @@ Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
6699
final String buildDir = getBuildDirectory();
67100
final String osName = targetOS.name;
68101
final Uri buildUri = projectUri.resolve('$buildDir/native_assets/$osName/');
69-
final Uri nativeAssetsFileUri = buildUri.resolve('native_assets.json');
102+
final Uri nativeAssetsFileUri = buildUri.resolve(_nativeAssetsJsonFileName);
70103

71-
final environmentDefines = <String, String>{kBuildMode: buildInfo.mode.cliName};
104+
final environmentDefines = <String, String>{kBuildMode: mode.cliName};
72105

73106
// First perform the dart build.
74107
final DartHooksResult dartHookResult = await runFlutterSpecificHooks(
@@ -93,9 +126,68 @@ Future<Uri?> testCompilerBuildNativeAssets(BuildInfo buildInfo) async {
93126
projectUri: projectUri,
94127
fileSystem: globals.fs,
95128
nativeAssetsFileUri: nativeAssetsFileUri,
96-
targetUri: projectUri.resolve('${getBuildDirectory()}/native_assets/$osName/'),
129+
targetUri: buildUri,
97130
);
98131
assert(globals.fs.file(nativeAssetsFileUri).existsSync());
99132

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

0 commit comments

Comments
 (0)