[native assets] Create NativeAssetsManifest.json instead of kernel embedding (#159322)

This PR introduces a `NativeAssetsManifest.json` next to the
`AssetManifest.bin` and `FontManifest.json`. This removes the need for
embedding the native assets mapping inside the kernel file and enables
decoupling native assets building and bundling from the kernel
compilation in flutter tools. This means `flutter run` no longer does a
dry run of `hook/build.dart` hooks.

(It also means all isolate groups will have the same native assets.
However, since Flutter does not support `Isolate.spawnUri` from kernel
files, this is not a regression.)

Implementation details:

* g3 is still using kernel embedding.
https://github.com/flutter/flutter/pull/142016 introduced an argument to
embed a `native_assets.yaml` inside `flutter attach` and `flutter run`
(the outer flutter process), but it is not used in `flutter assemble`
(the inner process when doing `flutter run`). So, those arguments need
to still be respected. However, all other logic related to embedding a
yaml encoding in the kernel file has been removed.
* All dry-run logic has been removed. 🎉 
* The `KernelSnapshot` target no longer depends on the
`InstallCodeAssets` target. Instead, the various OS-specific
"BundleAsset" targets now depend on the `InstallCodeAssets` target. The
`InstallCodeAssets` invokes the build hooks and produces the
`NativeAssetsManifest.json`. The various "BundleAsset" commands
synchronize the `NativeAssetsManifest.json` to the app bundle.
* `InstallCodeAssets` produces a `native_assets.json`, which is renamed
to `NativeAssetsManifest.json` in the various "Bundle" targets. This
means that all unit tests of the "Bundle" targets now need to create
this file. (Similar to how `app.dill` is expected to exist because
`KernelSnapshot` is a dependency of the "Bundle" targets.)
* Because dynamic libraries need to be code signed (at least on iOS and
MacOS), the bundling of the dylibs is _not_ migrated to reuse
`_updateDevFS` (which is used for ordinary assets). Only the 2nd and 3rd
invocation of `flutter assemble` from `xcodebuild` has access to the
code signing identity.

Relevant tests:

* test/integration.shard/isolated/native_assets_test.dart - runs
`flutter run` with native assets including hot restart and hot reload.

TODO:

* Undo engine-roll in this PR after engine has rolled in.

Issue:

* https://github.com/flutter/flutter/issues/154425

Related PRs:

* https://dart-review.googlesource.com/c/sdk/+/388161
* https://github.com/flutter/engine/pull/56727

## Pre-launch Checklist

- [x] I read the [Contributor Guide] and followed the process outlined
there for submitting PRs.
- [x] I read the [Tree Hygiene] wiki page, which explains my
responsibilities.
- [x] I read and followed the [Flutter Style Guide], including [Features
we expect every widget to implement].
- [x] I signed the [CLA].
- [x] I listed at least one issue that this PR fixes in the description
above.
- [x] I updated/added relevant documentation (doc comments with `///`).
- [x] I added new tests to check the change I am making, or this PR is
[test-exempt].
- [x] I followed the [breaking change policy] and added [Data Driven
Fixes] where supported.
- [x] All existing and new tests are passing.

<!-- Links -->
[Contributor Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview
[Tree Hygiene]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md
[test-exempt]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests
[Flutter Style Guide]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md
[Features we expect every widget to implement]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement
[CLA]: https://cla.developers.google.com/
[flutter/tests]: https://github.com/flutter/tests
[breaking change policy]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes
[Discord]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md
[Data Driven Fixes]:
https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md
This commit is contained in:
Daco Harkes
2024-11-27 12:03:19 +01:00
committed by GitHub
parent c6260a86f6
commit 4aa2caef20
39 changed files with 197 additions and 954 deletions

View File

@@ -1258,7 +1258,6 @@ class FakeHotRunnerFactory extends Fake implements HotRunnerFactory {
FlutterProject? flutterProject,
Analytics? analytics,
String? nativeAssetsYamlFile,
HotRunnerNativeAssetsBuilder? nativeAssetsBuilder,
}) {
if (_artifactTester != null) {
for (final FlutterDevice device in devices) {

View File

@@ -27,7 +27,6 @@ import 'package:flutter_tools/src/macos/macos_ipad_device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/web/compile.dart';
import 'package:test/fake.dart';
@@ -1611,7 +1610,6 @@ class CapturingAppDomain extends AppDomain {
String? isolateFilter,
bool machine = true,
String? userIdentifier,
required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder,
}) async {
this.userIdentifier = userIdentifier;
enableDevTools = options.enableDevTools;

View File

@@ -52,6 +52,7 @@ void main() {
// create pre-requisites.
environment.buildDir.childFile('app.dill')
.writeAsStringSync('abcd');
environment.buildDir.childFile('native_assets.json').createSync();
fileSystem
.file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug))
.createSync(recursive: true);
@@ -96,6 +97,7 @@ void main() {
// create pre-requisites.
environment.buildDir.childFile('app.dill')
.writeAsStringSync('abcd');
environment.buildDir.childFile('native_assets.json').createSync();
fileSystem
.file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug))
.createSync(recursive: true);
@@ -185,6 +187,7 @@ void main() {
));
environment.buildDir.createSync(recursive: true);
environment.buildDir.childFile('app.dill').createSync();
environment.buildDir.childFile('native_assets.json').createSync();
const AndroidAot androidAot = AndroidAot(TargetPlatform.android_arm64, BuildMode.release);
await androidAot.build(environment);
@@ -223,6 +226,7 @@ void main() {
));
environment.buildDir.createSync(recursive: true);
environment.buildDir.childFile('app.dill').createSync();
environment.buildDir.childFile('native_assets.json').createSync();
const AndroidAot androidAot = AndroidAot(TargetPlatform.android_arm64, BuildMode.release);
await androidAot.build(environment);
@@ -264,6 +268,7 @@ void main() {
));
environment.buildDir.createSync(recursive: true);
environment.buildDir.childFile('app.dill').createSync();
environment.buildDir.childFile('native_assets.json').createSync();
await const AndroidAot(TargetPlatform.android_arm64, BuildMode.release)
.build(environment);
@@ -301,6 +306,7 @@ void main() {
));
environment.buildDir.createSync(recursive: true);
environment.buildDir.childFile('app.dill').createSync();
environment.buildDir.childFile('native_assets.json').createSync();
await const AndroidAot(TargetPlatform.android_arm64, BuildMode.release)
.build(environment);
@@ -518,6 +524,7 @@ void main() {
// create pre-requisites.
environment.buildDir.childFile('app.dill')
.writeAsStringSync('abcd');
environment.buildDir.childFile('native_assets.json').createSync();
fileSystem
.file(artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug))
.createSync(recursive: true);

View File

@@ -43,6 +43,7 @@ void main() {
},
);
fileSystem.file(environment.buildDir.childFile('app.dill')).createSync(recursive: true);
fileSystem.file(environment.buildDir.childFile('native_assets.json')).createSync(recursive: true);
fileSystem.file('packages/flutter_tools/lib/src/build_system/targets/assets.dart')
.createSync(recursive: true);
fileSystem.file('assets/foo/bar.png')

View File

@@ -12,7 +12,6 @@ import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/exceptions.dart';
import 'package:flutter_tools/src/build_system/targets/common.dart';
import 'package:flutter_tools/src/build_system/targets/ios.dart';
import 'package:flutter_tools/src/build_system/targets/native_assets.dart';
import 'package:flutter_tools/src/compile.dart';
import '../../../src/common.dart';
@@ -65,34 +64,14 @@ void main() {
iosEnvironment.buildDir.createSync(recursive: true);
});
testWithoutContext('KernelSnapshotProgram throws error if missing build mode', () async {
testWithoutContext('KernelSnapshot throws error if missing build mode', () async {
androidEnvironment.defines.remove(kBuildMode);
expect(
const KernelSnapshotProgram().build(androidEnvironment),
const KernelSnapshot().build(androidEnvironment),
throwsA(isA<MissingDefineException>()));
});
const String emptyNativeAssets = '''
format-version:
- 1
- 0
- 0
native-assets: {}
''';
const String nonEmptyNativeAssets = '''
format-version:
- 1
- 0
- 0
native-assets:
macos_arm64:
package:my_package/my_package_bindings_generated.dart:
- absolute
- my_package.framework/my_package
''';
testWithoutContext('KernelSnapshotProgram handles null result from kernel compilation', () async {
testWithoutContext('KernelSnapshot handles null result from kernel compilation', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -119,7 +98,7 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--verbosity=error',
@@ -127,11 +106,11 @@ native-assets:
], exitCode: 1),
]);
await expectLater(() => const KernelSnapshotProgram().build(androidEnvironment), throwsException);
await expectLater(() => const KernelSnapshot().build(androidEnvironment), throwsException);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram does use track widget creation on profile builds', () async {
testWithoutContext('KernelSnapshot does use track widget creation on profile builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -158,20 +137,20 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram().build(androidEnvironment);
await const KernelSnapshot().build(androidEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram correctly handles an empty string in ExtraFrontEndOptions', () async {
testWithoutContext('KernelSnapshot correctly handles an empty string in ExtraFrontEndOptions', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -198,21 +177,21 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram()
await const KernelSnapshot()
.build(androidEnvironment..defines[kExtraFrontEndOptions] = '');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram correctly forwards FrontendServerStarterPath', () async {
testWithoutContext('KernelSnapshot correctly forwards FrontendServerStarterPath', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -239,21 +218,21 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram()
await const KernelSnapshot()
.build(androidEnvironment..defines[kFrontendServerStarterPath] = 'path/to/frontend_server_starter.dart');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram correctly forwards ExtraFrontEndOptions', () async {
testWithoutContext('KernelSnapshot correctly forwards ExtraFrontEndOptions', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -280,23 +259,23 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--verbosity=error',
'foo',
'bar',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram()
await const KernelSnapshot()
.build(androidEnvironment..defines[kExtraFrontEndOptions] = 'foo,bar');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram can disable track-widget-creation on debug builds', () async {
testWithoutContext('KernelSnapshot can disable track-widget-creation on debug builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -320,25 +299,25 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--incremental',
'--initialize-from-dill',
'$build/program.dill',
'$build/app.dill',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram().build(androidEnvironment
await const KernelSnapshot().build(androidEnvironment
..defines[kBuildMode] = BuildMode.debug.cliName
..defines[kTrackWidgetCreation] = 'false');
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram forces platform linking on debug for darwin target platforms', () async {
testWithoutContext('KernelSnapshot forces platform linking on debug for darwin target platforms', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -360,18 +339,18 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--incremental',
'--initialize-from-dill',
'$build/program.dill',
'$build/app.dill',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotProgram().build(androidEnvironment
await const KernelSnapshot().build(androidEnvironment
..defines[kTargetPlatform] = getNameForTargetPlatform(TargetPlatform.darwin)
..defines[kBuildMode] = BuildMode.debug.cliName
..defines[kTrackWidgetCreation] = 'false'
@@ -380,7 +359,7 @@ native-assets:
expect(processManager, hasNoRemainingExpectations);
});
testWithoutContext('KernelSnapshotProgram does use track widget creation on debug builds', () async {
testWithoutContext('KernelSnapshot does use track widget creation on debug builds', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
@@ -415,92 +394,22 @@ native-assets:
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/program.dill',
'$build/app.dill',
'--depfile',
'$build/kernel_snapshot_program.d',
'--incremental',
'--initialize-from-dill',
'$build/program.dill',
'$build/app.dill',
'--verbosity=error',
'file:///lib/main.dart',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/program.dill 0\n'),
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey /build/653e11a8e6908714056a57cd6b4f602a/app.dill 0\n'),
]);
await const KernelSnapshotProgram().build(testEnvironment);
await const KernelSnapshot().build(testEnvironment);
expect(processManager, hasNoRemainingExpectations);
});
for (final BuildMode buildMode in <BuildMode>[BuildMode.debug, BuildMode.release]) {
for (final bool empty in <bool>[true, false]) {
final String testName = empty ? 'empty' : 'non empty';
testWithoutContext('KernelSnapshotNativeAssets ${buildMode.name} $testName', () async {
fileSystem.file('.dart_tool/package_config.json')
..createSync(recursive: true)
..writeAsStringSync('{"configVersion": 2, "packages":[]}');
androidEnvironment.buildDir.childFile(InstallCodeAssets.nativeAssetsFilename)
..createSync(recursive: true)
..writeAsStringSync(empty ? emptyNativeAssets : nonEmptyNativeAssets);
final String build = androidEnvironment.buildDir.path;
final String flutterPatchedSdkPath = artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath,
platform: TargetPlatform.darwin,
mode: buildMode,
);
processManager.addCommands(<FakeCommand>[
if (!empty)
FakeCommand(command: <String>[
artifacts.getArtifactPath(Artifact.engineDartAotRuntime),
artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk),
'--sdk-root',
'$flutterPatchedSdkPath/',
'--target=flutter',
'--no-print-incremental-dependencies',
...buildModeOptions(buildMode, <String>[]),
'--no-link-platform',
if (buildMode == BuildMode.release) ...<String>['--aot', '--tfa'],
'--packages',
'/.dart_tool/package_config.json',
'--output-dill',
'$build/native_assets.dill',
'--native-assets',
'$build/${InstallCodeAssets.nativeAssetsFilename}',
'--verbosity=error',
'--native-assets-only',
], stdout: 'result $kBoundaryKey\n$kBoundaryKey\n$kBoundaryKey $build/app.dill 0\n'),
]);
await const KernelSnapshotNativeAssets().build(androidEnvironment
..defines[kTargetPlatform] = getNameForTargetPlatform(TargetPlatform.darwin)
..defines[kBuildMode] = buildMode.cliName
);
expect(processManager, hasNoRemainingExpectations);
});
}
}
for (final bool empty in <bool>[true, false]) {
final String testName = empty ? 'empty' : 'non empty';
testWithoutContext('KernelSnapshot native assets $testName', () async {
const List<int> programDillBytes = <int>[1, 2, 3, 4];
androidEnvironment.buildDir.childFile('program.dill')
..createSync(recursive: true)
..writeAsBytesSync(programDillBytes);
final List<int> nativeAssetsDillBytes = empty ? <int>[] : <int>[5, 6, 7, 8];
androidEnvironment.buildDir.childFile('native_assets.dill')
..createSync(recursive: true)
..writeAsBytesSync(nativeAssetsDillBytes);
await const KernelSnapshot().build(androidEnvironment);
expect(
androidEnvironment.buildDir.childFile('app.dill').readAsBytesSync(),
equals(<int>[...programDillBytes, ...nativeAssetsDillBytes]),
);
});
}
testUsingContext('AotElfProfile Produces correct output directory', () async {
final String build = androidEnvironment.buildDir.path;
processManager.addCommands(<FakeCommand>[
@@ -520,6 +429,7 @@ native-assets:
]),
]);
androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true);
androidEnvironment.buildDir.childFile('native_assets.json').createSync();
await const AotElfProfile(TargetPlatform.android_arm).build(androidEnvironment);
@@ -548,6 +458,7 @@ native-assets:
]),
]);
androidEnvironment.buildDir.childFile('app.dill').createSync(recursive: true);
androidEnvironment.buildDir.childFile('native_assets.json').createSync();
await const AotElfRelease(TargetPlatform.android_arm).build(androidEnvironment);

View File

@@ -205,6 +205,7 @@ void main() {
.createSync(recursive: true);
// App kernel
environment.buildDir.childFile('app.dill').createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync();
// Stub framework
environment.buildDir
.childDirectory('App.framework')
@@ -285,6 +286,7 @@ void main() {
fileSystem.file('shader.glsl').writeAsStringSync('test');
// App kernel
environment.buildDir.childFile('app.dill').createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync();
// Stub framework
environment.buildDir
.childDirectory('App.framework')
@@ -360,6 +362,7 @@ void main() {
.childDirectory('App.framework')
.childFile('App')
.createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync();
// Input dSYM
environment.buildDir
@@ -425,6 +428,7 @@ void main() {
.childDirectory('App.framework')
.childFile('App')
.createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync();
final Directory frameworkDirectory = environment.outputDir.childDirectory('App.framework');
final File frameworkDirectoryBinary = frameworkDirectory.childFile('App');

View File

@@ -116,6 +116,7 @@ void main() {
// Create input files.
testEnvironment.buildDir.childFile('app.dill').createSync();
testEnvironment.buildDir.childFile('native_assets.json').createSync();
fileSystem.file('bundle.sksl').writeAsStringSync(json.encode(
<String, Object>{
'engineRevision': '2',
@@ -169,6 +170,7 @@ void main() {
// Create input files.
testEnvironment.buildDir.childFile('app.so').createSync();
testEnvironment.buildDir.childFile('native_assets.json').createSync();
await const LinuxAotBundle(AotElfProfile(TargetPlatform.linux_x64)).build(testEnvironment);
await const ProfileBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment);
@@ -208,6 +210,7 @@ void main() {
// Create input files.
testEnvironment.buildDir.childFile('app.so').createSync();
testEnvironment.buildDir.childFile('native_assets.json').createSync();
await const LinuxAotBundle(AotElfRelease(TargetPlatform.linux_x64)).build(testEnvironment);
await const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64).build(testEnvironment);

View File

@@ -418,6 +418,7 @@ void main() {
fileSystem.file(inputKernel)
..createSync(recursive: true)
..writeAsStringSync('testing');
environment.buildDir.childFile('native_assets.json').createSync();
await const DebugMacOSBundleFlutterAssets().build(environment);
@@ -454,6 +455,9 @@ void main() {
.createSync(recursive: true);
fileSystem.file('${environment.buildDir.path}/App.framework/App')
.createSync(recursive: true);
fileSystem
.file('${environment.buildDir.path}/native_assets.json')
.createSync();
await const ProfileMacOSBundleFlutterAssets().build(environment..defines[kBuildMode] = 'profile');
@@ -483,6 +487,9 @@ void main() {
.createSync(recursive: true);
fileSystem.file('${environment.buildDir.path}/App.framework.dSYM/Contents/Resources/DWARF/App')
.createSync(recursive: true);
fileSystem
.file('${environment.buildDir.path}/native_assets.json')
.createSync();
await const ReleaseMacOSBundleFlutterAssets()
.build(environment..defines[kBuildMode] = 'release');
@@ -504,6 +511,9 @@ void main() {
final File inputFramework = fileSystem.file(fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App'))
..createSync(recursive: true)
..writeAsStringSync('ABC');
fileSystem
.file(environment.buildDir.childFile('native_assets.json'))
.createSync();
await const ProfileMacOSBundleFlutterAssets().build(environment..defines[kBuildMode] = 'profile');
final File outputFramework = fileSystem.file(fileSystem.path.join(environment.outputDir.path, 'App.framework', 'App'));
@@ -529,6 +539,9 @@ void main() {
.createSync(recursive: true);
fileSystem.file(fileSystem.path.join(environment.buildDir.path, 'App.framework', 'App'))
.createSync(recursive: true);
fileSystem
.file(environment.buildDir.childFile('native_assets.json'))
.createSync();
await const ReleaseMacOSBundleFlutterAssets().build(environment);
expect(usage.events, contains(const TestUsageEvent('assemble', 'macos-archive', label: 'success')));

View File

@@ -136,6 +136,7 @@ void main() {
);
environment.buildDir.childFile('app.dill').createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync(recursive: true);
// sksl bundle
fileSystem.file('bundle.sksl').writeAsStringSync(json.encode(
<String, Object>{
@@ -173,6 +174,7 @@ void main() {
);
environment.buildDir.childFile('app.so').createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync(recursive: true);
await const WindowsAotBundle(AotElfProfile(TargetPlatform.windows_x64)).build(environment);
await const ProfileBundleWindowsAssets(TargetPlatform.windows_x64).build(environment);
@@ -200,6 +202,7 @@ void main() {
);
environment.buildDir.childFile('app.so').createSync(recursive: true);
environment.buildDir.childFile('native_assets.json').createSync(recursive: true);
await const WindowsAotBundle(AotElfRelease(TargetPlatform.windows_x64)).build(environment);
await const ReleaseBundleWindowsAssets(TargetPlatform.windows_x64).build(environment);

View File

@@ -116,7 +116,7 @@ void main() {
]),
);
expect(environment.buildDir.childFile('native_assets.yaml'), exists);
expect(environment.buildDir.childFile('native_assets.json'), exists);
expect(buildRunner.buildInvocations, 1);
expect(
buildRunner.linkInvocations,

View File

@@ -104,7 +104,7 @@ void main() {
for (final bool isNativeAssetsEnabled in <bool>[true, false]) {
final String postFix = isNativeAssetsEnabled ? 'enabled' : 'disabled';
testUsingContext(
'Successful native_assets.yaml and native_assets.d creation with feature $postFix',
'Successful native_assets.json and native_assets.d creation with feature $postFix',
overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,

View File

@@ -2,12 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_info.dart' hide BuildMode;
import 'package:flutter_tools/src/isolated/native_assets/native_assets.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:native_assets_builder/native_assets_builder.dart';
import 'package:native_assets_cli/code_assets_builder.dart';
import 'package:package_config/package_config_types.dart';
@@ -23,7 +18,6 @@ class FakeFlutterNativeAssetsBuildRunner
this.packagesWithNativeAssetsResult = const <Package>[],
this.onBuild,
this.onLink,
this.buildDryRunResult = const FakeFlutterNativeAssetsBuilderResult(),
this.buildResult = const FakeFlutterNativeAssetsBuilderResult(),
this.linkResult = const FakeFlutterNativeAssetsBuilderResult(),
CCompilerConfig? cCompilerConfigResult,
@@ -36,14 +30,12 @@ class FakeFlutterNativeAssetsBuildRunner
final LinkResult? Function(LinkConfig)? onLink;
final BuildResult? buildResult;
final LinkResult? linkResult;
final BuildDryRunResult? buildDryRunResult;
final bool hasPackageConfigResult;
final List<Package> packagesWithNativeAssetsResult;
final CCompilerConfig cCompilerConfigResult;
final CCompilerConfig ndkCCompilerConfigResult;
int buildInvocations = 0;
int buildDryRunInvocations = 0;
int linkInvocations = 0;
int hasPackageConfigInvocations = 0;
int packagesWithNativeAssetsInvocations = 0;
@@ -128,19 +120,6 @@ class FakeFlutterNativeAssetsBuildRunner
return result;
}
@override
Future<BuildDryRunResult?> buildDryRun({
required List<String> supportedAssetTypes,
required ConfigCreator configCreator,
required BuildValidator buildValidator,
required bool includeParentEnvironment,
required OS targetOS,
required Uri workingDirectory,
}) async {
buildDryRunInvocations++;
return buildDryRunResult;
}
@override
Future<bool> hasPackageConfig() async {
hasPackageConfigInvocations++;
@@ -161,7 +140,7 @@ class FakeFlutterNativeAssetsBuildRunner
}
final class FakeFlutterNativeAssetsBuilderResult
implements BuildResult, BuildDryRunResult, LinkResult {
implements BuildResult, LinkResult {
const FakeFlutterNativeAssetsBuilderResult({
this.encodedAssets = const <EncodedAsset>[],
this.encodedAssetsForLinking = const <String, List<EncodedAsset>>{},
@@ -197,30 +176,3 @@ final class FakeFlutterNativeAssetsBuilderResult
@override
final List<Uri> dependencies;
}
class FakeHotRunnerNativeAssetsBuilder implements HotRunnerNativeAssetsBuilder {
FakeHotRunnerNativeAssetsBuilder(this.buildRunner);
final FlutterNativeAssetsBuildRunner buildRunner;
@override
Future<Uri?> dryRun({
required Uri projectUri,
required FileSystem fileSystem,
required List<FlutterDevice> flutterDevices,
required String packageConfigPath,
required PackageConfig packageConfig,
required Logger logger,
}) {
final List<TargetPlatform> targetPlatforms = flutterDevices
.map((FlutterDevice d) => d.targetPlatform)
.nonNulls
.toList();
return runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
buildRunner: buildRunner,
targetPlatforms: targetPlatforms,
);
}
}

View File

@@ -1,182 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/features.dart';
import 'package:flutter_tools/src/resident_devtools_handler.dart';
import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/run_hot.dart';
import 'package:native_assets_cli/code_assets_builder.dart';
import 'package:package_config/package_config.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
import '../hot_shared.dart';
import 'fake_native_assets_build_runner.dart';
void main() {
group('native assets', () {
late TestHotRunnerConfig testingConfig;
late MemoryFileSystem fileSystem;
late FakeAnalytics fakeAnalytics;
setUp(() {
fileSystem = MemoryFileSystem.test();
testingConfig = TestHotRunnerConfig(
successfulHotRestartSetup: true,
);
fakeAnalytics = getInitializedFakeAnalyticsInstance(
fs: fileSystem,
fakeFlutterVersion: FakeFlutterVersion(),
);
});
testUsingContext('native assets restart', () async {
final FakeDevice device = FakeDevice();
final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
final List<FlutterDevice> devices = <FlutterDevice>[
fakeFlutterDevice,
];
fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
success: true,
invalidatedSourcesCount: 6,
syncedBytes: 8,
scannedSourcesCount: 16,
compileDuration: const Duration(seconds: 16),
transferDuration: const Duration(seconds: 32),
);
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', fileSystem.currentDirectory.uri),
],
buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(
codeAssets: <CodeAsset>[
CodeAsset(
package: 'bar',
name: 'bar.dart',
linkMode: DynamicLoadingBundled(),
os: OS.macOS,
architecture: Architecture.arm64,
file: Uri.file('bar.dylib'),
),
CodeAsset(
package: 'bar',
name: 'bar.dart',
linkMode: DynamicLoadingBundled(),
os: OS.macOS,
architecture: Architecture.x64,
file: Uri.file('bar.dylib'),
),
],
),
);
final HotRunner hotRunner = HotRunner(
devices,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner),
analytics: fakeAnalytics,
);
final OperationResult result = await hotRunner.restart(fullRestart: true);
expect(result.isOk, true);
// Hot restart does not require rerunning anything for native assets.
// The previous native assets mapping should be used.
expect(buildRunner.buildInvocations, 0);
expect(buildRunner.buildDryRunInvocations, 0);
expect(buildRunner.linkInvocations, 0);
expect(buildRunner.hasPackageConfigInvocations, 0);
expect(buildRunner.packagesWithNativeAssetsInvocations, 0);
}, overrides: <Type, Generator>{
HotRunnerConfig: () => testingConfig,
Artifacts: () => Artifacts.test(),
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.empty(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true),
});
testUsingContext('native assets run unsupported', () async {
final FakeDevice device = FakeDevice(targetPlatform: TargetPlatform.fuchsia_arm64);
final FakeFlutterDevice fakeFlutterDevice = FakeFlutterDevice(device);
final List<FlutterDevice> devices = <FlutterDevice>[
fakeFlutterDevice,
];
fakeFlutterDevice.updateDevFSReportCallback = () async => UpdateFSReport(
success: true,
invalidatedSourcesCount: 6,
syncedBytes: 8,
scannedSourcesCount: 16,
compileDuration: const Duration(seconds: 16),
transferDuration: const Duration(seconds: 32),
);
(fakeFlutterDevice.devFS! as FakeDevFs).baseUri = Uri.parse('file:///base_uri');
final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', fileSystem.currentDirectory.uri),
],
buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(
codeAssets: <CodeAsset>[
CodeAsset(
package: 'bar',
name: 'bar.dart',
linkMode: DynamicLoadingBundled(),
os: OS.macOS,
architecture: Architecture.arm64,
file: Uri.file('bar.dylib'),
),
CodeAsset(
package: 'bar',
name: 'bar.dart',
linkMode: DynamicLoadingBundled(),
os: OS.macOS,
architecture: Architecture.x64,
file: Uri.file('bar.dylib'),
),
],
),
);
final HotRunner hotRunner = HotRunner(
devices,
debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner),
analytics: fakeAnalytics,
);
expect(
() => hotRunner.run(),
throwsToolExit( message:
'Package(s) bar require the native assets feature. '
'This feature has not yet been implemented for `TargetPlatform.fuchsia_arm64`. '
'For more info see https://github.com/flutter/flutter/issues/129757.',
)
);
}, overrides: <Type, Generator>{
HotRunnerConfig: () => testingConfig,
Artifacts: () => Artifacts.test(),
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.empty(),
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true, isMacOSEnabled: true),
});
});
}

View File

@@ -47,26 +47,6 @@ void main() {
projectUri = environment.projectDir.uri;
});
testUsingContext('dry run with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
expect(
await runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[TargetPlatform.windows_x64],
buildRunner: FakeFlutterNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
),
null,
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('build with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
@@ -87,97 +67,6 @@ void main() {
);
});
testUsingContext('dry run for multiple OSes with no package config', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
await runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[
TargetPlatform.windows_x64,
TargetPlatform.darwin,
TargetPlatform.ios,
],
buildRunner: FakeFlutterNativeAssetsBuildRunner(
hasPackageConfigResult: false,
),
);
expect(
(globals.logger as BufferLogger).traceText,
contains('No package config found. Skipping native assets compilation.'),
);
});
testUsingContext('dry run with assets but not enabled', overrides: <Type, Generator>{
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[TargetPlatform.windows_x64],
buildRunner: FakeFlutterNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
),
),
throwsToolExit(
message: 'Package(s) bar require the native assets feature to be enabled. '
'Enable using `flutter config --enable-native-assets`.',
),
);
});
testUsingContext('dry run with assets', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
buildDryRunResult: FakeFlutterNativeAssetsBuilderResult.fromAssets(
codeAssets: <CodeAsset>[
CodeAsset(
package: 'bar',
name: 'bar.dart',
linkMode: DynamicLoadingBundled(),
os: OS.windows,
file: Uri.file('bar.dll'),
),
],
),
);
final Uri? nativeAssetsYaml = await runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[TargetPlatform.windows_x64],
buildRunner: buildRunner,
);
expect(
(globals.logger as BufferLogger).traceText,
stringContainsInOrder(<String>[
'Dry running native assets for windows.',
'Dry running native assets for windows done.',
]),
);
expect(
nativeAssetsYaml,
projectUri.resolve('build/native_assets/windows/${InstallCodeAssets.nativeAssetsFilename}'),
);
expect(
await fileSystem.file(nativeAssetsYaml).readAsString(),
contains('package:bar/bar.dart'),
);
expect(buildRunner.buildDryRunInvocations, 1);
});
testUsingContext('Native assets: non-bundled libraries require no copying', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
@@ -185,7 +74,7 @@ void main() {
}, () async {
final File packageConfig =
environment.projectDir.childFile('.dart_tool/package_config.json');
final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.yaml').uri;
final Uri nonFlutterTesterAssetUri = environment.buildDir.childFile('native_assets.json').uri;
await packageConfig.parent.create();
await packageConfig.create();
@@ -302,33 +191,6 @@ void main() {
);
});
testUsingContext('Native assets dry run error', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),
}, () async {
final File packageConfig =
environment.projectDir.childFile('.dart_tool/package_config.json');
await packageConfig.parent.create();
await packageConfig.create();
expect(
() => runFlutterSpecificDartDryRunOnPlatforms(
projectUri: projectUri,
fileSystem: fileSystem,
targetPlatforms: <TargetPlatform>[TargetPlatform.windows_x64],
buildRunner: FakeFlutterNativeAssetsBuildRunner(
packagesWithNativeAssetsResult: <Package>[
Package('bar', projectUri),
],
buildDryRunResult: null,
),
),
throwsToolExit(
message:
'Building (dry run) native assets failed. See the logs for more details.',
),
);
});
testUsingContext('Native assets build error', overrides: <Type, Generator>{
FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true),
ProcessManager: () => FakeProcessManager.empty(),

View File

@@ -17,7 +17,6 @@ import '../../src/fake_vm_services.dart';
import '../../src/fakes.dart';
import '../../src/testbed.dart';
import '../resident_runner_helpers.dart';
import 'fake_native_assets_build_runner.dart';
void main() {
late Testbed testbed;
@@ -55,8 +54,7 @@ void main() {
]);
globals.fs
.file(globals.fs.path.join('lib', 'main.dart'))
.createSync(recursive: true);
final FakeFlutterNativeAssetsBuildRunner buildRunner = FakeFlutterNativeAssetsBuildRunner();
.createSync(recursive: true);
final HotRunner residentRunner = HotRunner(
<FlutterDevice>[
flutterDevice,
@@ -71,7 +69,6 @@ void main() {
)),
target: 'main.dart',
devtoolsHandler: createNoOpHandler,
nativeAssetsBuilder: FakeHotRunnerNativeAssetsBuilder(buildRunner),
analytics: FakeAnalytics(),
nativeAssetsYamlFile: 'foo.yaml',
);
@@ -79,12 +76,6 @@ void main() {
final int result = await residentRunner.run();
expect(result, 0);
expect(buildRunner.buildInvocations, 0);
expect(buildRunner.buildDryRunInvocations, 0);
expect(buildRunner.linkInvocations, 0);
expect(buildRunner.hasPackageConfigInvocations, 0);
expect(buildRunner.packagesWithNativeAssetsInvocations, 0);
expect(residentCompiler.recompileCalled, true);
expect(residentCompiler.receivedNativeAssetsYaml, globals.fs.path.toUri('foo.yaml'));
}),

View File

@@ -145,7 +145,10 @@ void main() {
'package:bar/bar.dart',
if (flutterTester)
// Tests run on host system, so the have the full path on the system.
projectUri.resolve('build/native_assets/$expectedDirectory/bar.dll').toFilePath()
projectUri
.resolve('build/native_assets/$expectedDirectory/bar.dll')
.toFilePath()
.replaceAll(r'\', r'\\') // Undo JSON string escaping.
else
// Apps are a bundle with the dylibs on their dlopen path.
'bar.dll',