Revert "Speed up first asset load by encoding asset manifest in binary rather than JSON (#113637)" (#116662)

This reverts commit 56cad89b1e.
This commit is contained in:
Casey Hillers
2022-12-07 09:29:05 -08:00
committed by GitHub
parent 352ad3a9ef
commit 7673108d7e
14 changed files with 896 additions and 2054 deletions

View File

@@ -2,11 +2,8 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:standard_message_codec/standard_message_codec.dart';
import 'base/context.dart';
import 'base/deferred_component.dart';
@@ -139,9 +136,6 @@ class ManifestAssetBundle implements AssetBundle {
_splitDeferredAssets = splitDeferredAssets,
_licenseCollector = LicenseCollector(fileSystem: fileSystem);
// We assume the main asset is designed for a device pixel ratio of 1.0
static const double _defaultResolution = 1.0;
final Logger _logger;
final FileSystem _fileSystem;
final LicenseCollector _licenseCollector;
@@ -167,8 +161,7 @@ class ManifestAssetBundle implements AssetBundle {
DateTime? _lastBuildTimestamp;
static const String _kAssetManifestBinFileName = 'AssetManifest.bin';
static const String _kAssetManifestJsonFileName = 'AssetManifest.json';
static const String _kAssetManifestJson = 'AssetManifest.json';
static const String _kNoticeFile = 'NOTICES';
// Comically, this can't be name with the more common .gz file extension
// because when it's part of an AAR and brought into another APK via gradle,
@@ -236,13 +229,8 @@ class ManifestAssetBundle implements AssetBundle {
// device.
_lastBuildTimestamp = DateTime.now();
if (flutterManifest.isEmpty) {
entries[_kAssetManifestJsonFileName] = DevFSStringContent('{}');
entryKinds[_kAssetManifestJsonFileName] = AssetKind.regular;
final ByteData emptyAssetManifest =
const StandardMessageCodec().encodeMessage(<dynamic, dynamic>{})!;
entries[_kAssetManifestBinFileName] =
DevFSByteContent(emptyAssetManifest.buffer.asUint8List(0, emptyAssetManifest.lengthInBytes));
entryKinds[_kAssetManifestBinFileName] = AssetKind.regular;
entries[_kAssetManifestJson] = DevFSStringContent('{}');
entryKinds[_kAssetManifestJson] = AssetKind.regular;
return 0;
}
@@ -439,11 +427,7 @@ class ManifestAssetBundle implements AssetBundle {
_wildcardDirectories[uri] ??= _fileSystem.directory(uri);
}
final Map<String, List<String>> assetManifest =
_createAssetManifest(assetVariants, deferredComponentsAssetVariants);
final DevFSStringContent assetManifestJson = DevFSStringContent(json.encode(assetManifest));
final DevFSByteContent assetManifestBinary = _createAssetManifestBinary(assetManifest);
final DevFSStringContent assetManifest = _createAssetManifest(assetVariants, deferredComponentsAssetVariants);
final DevFSStringContent fontManifest = DevFSStringContent(json.encode(fonts));
final LicenseResult licenseResult = _licenseCollector.obtainLicenses(packageConfig, additionalLicenseFiles);
if (licenseResult.errorMessages.isNotEmpty) {
@@ -467,8 +451,7 @@ class ManifestAssetBundle implements AssetBundle {
_fileSystem.file('DOES_NOT_EXIST_RERUN_FOR_WILDCARD$suffix').absolute);
}
_setIfChanged(_kAssetManifestJsonFileName, assetManifestJson, AssetKind.regular);
_setIfChanged(_kAssetManifestBinFileName, assetManifestBinary, AssetKind.regular);
_setIfChanged(_kAssetManifestJson, assetManifest, AssetKind.regular);
_setIfChanged(kFontManifestJson, fontManifest, AssetKind.regular);
_setLicenseIfChanged(licenseResult.combinedLicenses, targetPlatform);
return 0;
@@ -477,31 +460,17 @@ class ManifestAssetBundle implements AssetBundle {
@override
List<File> additionalDependencies = <File>[];
void _setIfChanged(String key, DevFSContent content, AssetKind assetKind) {
bool areEqual(List<int> o1, List<int> o2) {
if (o1.length != o2.length) {
return false;
}
for (int index = 0; index < o1.length; index++) {
if (o1[index] != o2[index]) {
return false;
}
}
return true;
}
final DevFSContent? oldContent = entries[key];
// In the case that the content is unchanged, we want to avoid an overwrite
// as the isModified property may be reset to true,
if (oldContent is DevFSByteContent && content is DevFSByteContent &&
areEqual(oldContent.bytes, content.bytes)) {
void _setIfChanged(String key, DevFSStringContent content, AssetKind assetKind) {
if (!entries.containsKey(key)) {
entries[key] = content;
entryKinds[key] = assetKind;
return;
}
entries[key] = content;
entryKinds[key] = assetKind;
final DevFSStringContent? oldContent = entries[key] as DevFSStringContent?;
if (oldContent?.string != content.string) {
entries[key] = content;
entryKinds[key] = assetKind;
}
}
void _setLicenseIfChanged(
@@ -653,14 +622,14 @@ class ManifestAssetBundle implements AssetBundle {
return deferredComponentsAssetVariants;
}
Map<String, List<String>> _createAssetManifest(
DevFSStringContent _createAssetManifest(
Map<_Asset, List<_Asset>> assetVariants,
Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants
) {
final Map<String, List<String>> manifest = <String, List<String>>{};
final Map<_Asset, List<String>> entries = <_Asset, List<String>>{};
final Map<String, List<String>> jsonObject = <String, List<String>>{};
final Map<_Asset, List<String>> jsonEntries = <_Asset, List<String>>{};
assetVariants.forEach((_Asset main, List<_Asset> variants) {
entries[main] = <String>[
jsonEntries[main] = <String>[
for (final _Asset variant in variants)
variant.entryUri.path,
];
@@ -668,69 +637,26 @@ class ManifestAssetBundle implements AssetBundle {
if (deferredComponentsAssetVariants != null) {
for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) {
componentAssets.forEach((_Asset main, List<_Asset> variants) {
entries[main] = <String>[
jsonEntries[main] = <String>[
for (final _Asset variant in variants)
variant.entryUri.path,
];
});
}
}
final List<_Asset> sortedKeys = entries.keys.toList()
final List<_Asset> sortedKeys = jsonEntries.keys.toList()
..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path));
for (final _Asset main in sortedKeys) {
final String decodedEntryPath = Uri.decodeFull(main.entryUri.path);
final List<String> rawEntryVariantsPaths = entries[main]!;
final List<String> rawEntryVariantsPaths = jsonEntries[main]!;
final List<String> decodedEntryVariantPaths = rawEntryVariantsPaths
.map((String value) => Uri.decodeFull(value))
.toList();
manifest[decodedEntryPath] = decodedEntryVariantPaths;
jsonObject[decodedEntryPath] = decodedEntryVariantPaths;
}
return manifest;
return DevFSStringContent(json.encode(jsonObject));
}
DevFSByteContent _createAssetManifestBinary(
Map<String, List<String>> assetManifest
) {
double parseScale(String key) {
final Uri assetUri = Uri.parse(key);
String directoryPath = '';
if (assetUri.pathSegments.length > 1) {
directoryPath = assetUri.pathSegments[assetUri.pathSegments.length - 2];
}
final Match? match = _extractRatioRegExp.firstMatch(directoryPath);
if (match != null && match.groupCount > 0) {
return double.parse(match.group(1)!);
}
return _defaultResolution;
}
final Map<String, dynamic> result = <String, dynamic>{};
for (final MapEntry<String, dynamic> manifestEntry in assetManifest.entries) {
final List<dynamic> resultVariants = <dynamic>[];
final List<String> entries = (manifestEntry.value as List<dynamic>).cast<String>();
for (final String variant in entries) {
if (variant == manifestEntry.key) {
// With the newer binary format, don't include the main asset in it's
// list of variants. This reduces parsing time at runtime.
continue;
}
final Map<String, dynamic> resultVariant = <String, dynamic>{};
final double variantDevicePixelRatio = parseScale(variant);
resultVariant['asset'] = variant;
resultVariant['dpr'] = variantDevicePixelRatio;
resultVariants.add(resultVariant);
}
result[manifestEntry.key] = resultVariants;
}
final ByteData message = const StandardMessageCodec().encodeMessage(result)!;
return DevFSByteContent(message.buffer.asUint8List(0, message.lengthInBytes));
}
static final RegExp _extractRatioRegExp = RegExp(r'/?(\d+(\.\d*)?)x$');
/// Prefixes family names and asset paths of fonts included from packages with
/// 'packages/<package_name>'
List<Font> _parsePackageFonts(

View File

@@ -57,8 +57,6 @@ dependencies:
vm_service: 9.4.0
standard_message_codec: 0.0.1+3
_fe_analyzer_shared: 50.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 5.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
@@ -90,6 +88,7 @@ dependencies:
watcher: 1.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies:
collection: 1.17.0
file_testing: 3.0.0
pubspec_parse: 1.2.1
@@ -98,10 +97,9 @@ dev_dependencies:
json_annotation: 4.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test: 1.22.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.17.0
dartdoc:
# Exclude this package from the hosted API docs.
nodoc: true
# PUBSPEC CHECKSUM: 408d
# PUBSPEC CHECKSUM: 65eb

View File

@@ -220,7 +220,7 @@ loading-units-spelled-wrong:
expect(logger.statusText, contains('Errors checking the following files:'));
expect(logger.statusText, contains("Invalid loading units yaml file, 'loading-units' entry did not exist."));
expect(logger.statusText, isNot(contains('Previously existing loading units no longer exist:\n\n LoadingUnit 2\n Libraries:\n - lib1\n')));
expect(logger.statusText.contains('Previously existing loading units no longer exist:\n\n LoadingUnit 2\n Libraries:\n - lib1\n'), false);
});
testWithoutContext('loadingUnitCache validator detects malformed file: not a list', () async {
@@ -382,7 +382,7 @@ loading-units:
validator.displayResults();
validator.attemptToolExit();
expect(logger.statusText, isNot(contains('Errors checking the following files:')));
expect(logger.statusText.contains('Errors checking the following files:'), false);
});
testWithoutContext('androidStringMapping modifies strings file', () async {
@@ -448,10 +448,9 @@ loading-units:
.childDirectory('main')
.childFile('AndroidManifest.xml');
expect(manifestOutput.existsSync(), true);
final String manifestOutputString = manifestOutput.readAsStringSync();
expect(manifestOutputString, contains('<meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="3:component1,2:component2,4:component2"/>'));
expect(manifestOutputString, isNot(contains('android:value="invalidmapping"')));
expect(manifestOutputString, contains("<!-- Don't delete the meta-data below."));
expect(manifestOutput.readAsStringSync().contains('<meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="3:component1,2:component2,4:component2"/>'), true);
expect(manifestOutput.readAsStringSync().contains('android:value="invalidmapping"'), false);
expect(manifestOutput.readAsStringSync().contains("<!-- Don't delete the meta-data below."), true);
});
testWithoutContext('androidStringMapping adds mapping when no existing mapping', () async {
@@ -696,8 +695,8 @@ loading-units:
.childDirectory('main')
.childFile('AndroidManifest.xml');
expect(manifestOutput.existsSync(), true);
expect(manifestOutput.readAsStringSync(), contains('<meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="3:component1,2:component2,4:component2"/>'));
expect(manifestOutput.readAsStringSync(), isNot(contains(RegExp(r'android:value[\s\n]*=[\s\n]*"invalidmapping"'))));
expect(manifestOutput.readAsStringSync(), contains("<!-- Don't delete the meta-data below."));
expect(manifestOutput.readAsStringSync().contains('<meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="3:component1,2:component2,4:component2"/>'), true);
expect(manifestOutput.readAsStringSync().contains(RegExp(r'android:value[\s\n]*=[\s\n]*"invalidmapping"')), false);
expect(manifestOutput.readAsStringSync().contains("<!-- Don't delete the meta-data below."), true);
});
}

View File

@@ -111,9 +111,8 @@ $fontsSection
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, containsAll(
<String>['AssetManifest.bin', 'AssetManifest.json', 'FontManifest.json', 'NOTICES.Z']
));
expect(bundle.entries.length, 3); // LICENSE, AssetManifest, FontManifest
expect(bundle.entries.containsKey('FontManifest.json'), isTrue);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(),

View File

@@ -3,7 +3,6 @@
// found in the LICENSE file.
import 'dart:convert';
import 'dart:typed_data';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/artifacts.dart';
@@ -14,7 +13,6 @@ import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/bundle_builder.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:standard_message_codec/standard_message_codec.dart';
import '../src/common.dart';
import '../src/context.dart';
@@ -50,16 +48,11 @@ void main() {
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json', 'AssetManifest.bin']));
const String expectedJsonAssetManifest = '{}';
expect(bundle.entries.length, 1);
const String expectedAssetManifest = '{}';
expect(
utf8.decode(await bundle.entries['AssetManifest.json']!.contentsAsBytes()),
expectedJsonAssetManifest,
);
const String expectedBinAssetManifest = '{}';
expect(
await _extractBinAssetManifestFromBundleAsJson(bundle),
expectedBinAssetManifest
expectedAssetManifest,
);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
@@ -79,8 +72,12 @@ flutter:
''');
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
expect(bundle.needsBuild(), false);
// Simulate modifying the files by updating the filestat time manually.
@@ -90,9 +87,13 @@ flutter:
expect(bundle.needsBuild(), true);
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt',
'assets/foo/fizz.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
// - assets/foo/fizz.txt
expect(bundle.entries.length, 5);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(),
@@ -111,8 +112,12 @@ flutter:
globals.fs.file('.packages').createSync();
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
expect(bundle.needsBuild(), false);
// Delete the wildcard directory and update pubspec file.
@@ -133,8 +138,12 @@ name: example''')
// supporting file deletion.
expect(bundle.needsBuild(), true);
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(),
@@ -157,8 +166,12 @@ flutter:
globals.fs.file('.packages').createSync();
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
expect(bundle.needsBuild(), false);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
@@ -190,8 +203,12 @@ flutter:
splitDeferredAssets: true,
).createBundle();
await bundle.build(packagesPath: '.packages', deferredComponentsEnabled: true);
expect(bundle.entries.keys, unorderedEquals(<String>['AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z', 'assets/foo/bar.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
expect(bundle.deferredComponentsEntries.length, 1);
expect(bundle.deferredComponentsEntries['component1']!.length, 2);
expect(bundle.needsBuild(), false);
@@ -220,9 +237,12 @@ flutter:
''');
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['assets/foo/bar.txt',
'assets/bar/barbie.txt', 'assets/wild/dash.txt', 'AssetManifest.json',
'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 6);
expect(bundle.deferredComponentsEntries.isEmpty, true);
expect(bundle.needsBuild(), false);
}, overrides: <Type, Generator>{
@@ -255,11 +275,14 @@ flutter:
splitDeferredAssets: true,
).createBundle();
await bundle.build(packagesPath: '.packages', deferredComponentsEnabled: true);
expect(bundle.entries.keys, unorderedEquals(<String>['assets/foo/bar.txt',
'AssetManifest.json', 'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z']));
expect(bundle.deferredComponentsEntries.keys, unorderedEquals(<String>['component1']));
expect(bundle.deferredComponentsEntries['component1']!.keys,
unorderedEquals(<String>['assets/bar/barbie.txt', 'assets/wild/dash.txt']));
// Expected assets:
// - asset manifest
// - font manifest
// - license file
// - assets/foo/bar.txt
expect(bundle.entries.length, 4);
expect(bundle.deferredComponentsEntries.length, 1);
expect(bundle.deferredComponentsEntries['component1']!.length, 2);
expect(bundle.needsBuild(), false);
// Simulate modifying the files by updating the filestat time manually.
@@ -270,13 +293,9 @@ flutter:
expect(bundle.needsBuild(), true);
await bundle.build(packagesPath: '.packages', deferredComponentsEnabled: true);
expect(bundle.entries.keys, unorderedEquals(<String>['assets/foo/bar.txt',
'AssetManifest.json', 'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z']));
expect(bundle.entries.length, 4);
expect(bundle.deferredComponentsEntries.length, 1);
expect(bundle.deferredComponentsEntries['component1']!.keys,
unorderedEquals(<String>['assets/bar/barbie.txt', 'assets/wild/dash.txt',
'assets/wild/fizz.txt']));
expect(bundle.deferredComponentsEntries['component1']!.length, 3);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(),
@@ -316,8 +335,7 @@ assets:
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(packagesPath: '.packages');
final DevFSContent? assetManifestBin = bundle.entries['AssetManifest.bin'];
final DevFSStringContent? assetManifestJson = bundle.entries['AssetManifest.json']
final DevFSStringContent? assetManifest = bundle.entries['AssetManifest.json']
as DevFSStringContent?;
final DevFSStringContent? fontManifest = bundle.entries['FontManifest.json']
as DevFSStringContent?;
@@ -326,8 +344,7 @@ assets:
await bundle.build(packagesPath: '.packages');
expect(assetManifestBin, bundle.entries['AssetManifest.bin']);
expect(assetManifestJson, bundle.entries['AssetManifest.json']);
expect(assetManifest, bundle.entries['AssetManifest.json']);
expect(fontManifest, bundle.entries['FontManifest.json']);
expect(license, bundle.entries['NOTICES']);
}, overrides: <Type, Generator>{
@@ -622,8 +639,7 @@ flutter:
await bundle.build(packagesPath: '.packages');
expect(bundle.entries.keys, unorderedEquals(<String>['packages/foo/bar/fizz.txt',
'AssetManifest.json', 'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z']));
expect(bundle.entries, hasLength(4));
expect(bundle.needsBuild(), false);
// Does not track dependency's wildcard directories.
@@ -723,7 +739,6 @@ flutter:
expect(await bundle.build(packagesPath: '.packages'), 0);
expect((bundle.entries['FontManifest.json']! as DevFSStringContent).string, '[]');
expect((bundle.entries['AssetManifest.json']! as DevFSStringContent).string, '{}');
expect(await _extractBinAssetManifestFromBundleAsJson(bundle), '{}');
expect(testLogger.errorText, contains(
'package:foo has `uses-material-design: true` set'
));
@@ -759,8 +774,7 @@ flutter:
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
expect(await bundle.build(packagesPath: '.packages'), 0);
expect(bundle.entries.keys, unorderedEquals(<String>['assets/foo.txt',
'AssetManifest.json', 'AssetManifest.bin', 'FontManifest.json', 'NOTICES.Z']));
expect(bundle.entries.length, 4);
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
@@ -798,17 +812,9 @@ flutter:
// The assets from deferred components and regular assets
// are both included in alphabetical order
expect((bundle.entries['AssetManifest.json']! as DevFSStringContent).string, '{"assets/apple.jpg":["assets/apple.jpg"],"assets/bar.jpg":["assets/bar.jpg"],"assets/foo.jpg":["assets/foo.jpg"],"assets/zebra.jpg":["assets/zebra.jpg"]}');
expect(await _extractBinAssetManifestFromBundleAsJson(bundle), '{"assets/apple.jpg":[],"assets/bar.jpg":[],"assets/foo.jpg":[],"assets/zebra.jpg":[]}');
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
Platform: () => FakePlatform(),
});
}
Future<String> _extractBinAssetManifestFromBundleAsJson(AssetBundle bundle) async {
final List<int> manifestBytes = await bundle.entries['AssetManifest.bin']!.contentsAsBytes();
return json.encode(const StandardMessageCodec().decodeMessage(
ByteData.sublistView(Uint8List.fromList(manifestBytes))
));
}

View File

@@ -3,7 +3,6 @@
// found in the LICENSE file.
import 'dart:convert';
import 'dart:typed_data';
import 'package:file/file.dart';
import 'package:file/memory.dart';
@@ -16,418 +15,209 @@ import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:standard_message_codec/standard_message_codec.dart';
import '../src/common.dart';
void main() {
// TODO(andrewkolos): Delete this group once we stop producing AssetManifest.json
// as part of build.
group('Legacy asset manifest (AssetManifest.json)', () {
Future<Map<String, List<String>>> extractAssetManifestFromBundle(ManifestAssetBundle bundle) async {
final String manifestJson = utf8.decode(await bundle.entries['AssetManifest.json']!.contentsAsBytes());
final Map<String, dynamic> parsedJson = json.decode(manifestJson) as Map<String, dynamic>;
final Iterable<String> keys = parsedJson.keys;
final Map<String, List<String>> parsedManifest = <String, List<String>> {
for (final String key in keys) key: List<String>.from(parsedJson[key] as List<dynamic>),
};
return parsedManifest;
}
Future<Map<String, List<String>>> extractAssetManifestFromBundle(ManifestAssetBundle bundle) async {
final String manifestJson = utf8.decode(await bundle.entries['AssetManifest.json']!.contentsAsBytes());
final Map<String, dynamic> parsedJson = json.decode(manifestJson) as Map<String, dynamic>;
final Iterable<String> keys = parsedJson.keys;
final Map<String, List<String>> parsedManifest = <String, List<String>> {
for (final String key in keys) key: List<String>.from(parsedJson[key] as List<dynamic>),
};
return parsedManifest;
}
group('AssetBundle asset variants (with Unix-style paths)', () {
late Platform platform;
late FileSystem fs;
group('AssetBundle asset variants (with Unix-style paths)', () {
late Platform platform;
late FileSystem fs;
setUp(() {
platform = FakePlatform();
fs = MemoryFileSystem.test();
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
setUp(() {
platform = FakePlatform();
fs = MemoryFileSystem.test();
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
fs.file('.packages').createSync();
fs.file('.packages').createSync();
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
sdk: flutter
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
assets:
- assets/
'''
);
});
testWithoutContext('Only images in folders named with device pixel ratios (e.g. 2x, 3.0x) should be considered as variants of other images', () async {
const String image = 'assets/image.jpg';
const String image2xVariant = 'assets/2x/image.jpg';
const String imageNonVariant = 'assets/notAVariant/image.jpg';
final List<String> assets = <String>[
image,
image2xVariant,
imageNonVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
expect(manifest, hasLength(2));
expect(manifest[image], equals(<String>[image, image2xVariant]));
expect(manifest[imageNonVariant], equals(<String>[imageNonVariant]));
});
testWithoutContext('Asset directories are recursively searched for assets', () async {
const String topLevelImage = 'assets/image.jpg';
const String secondLevelImage = 'assets/folder/secondLevel.jpg';
const String secondLevel2xVariant = 'assets/folder/2x/secondLevel.jpg';
final List<String> assets = <String>[
topLevelImage,
secondLevelImage,
secondLevel2xVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
expect(manifest, hasLength(2));
expect(manifest[topLevelImage], equals(<String>[topLevelImage]));
expect(manifest[secondLevelImage], equals(<String>[secondLevelImage, secondLevel2xVariant]));
});
testWithoutContext('Asset paths should never be URI-encoded', () async {
const String image = 'assets/normalFolder/i have URI-reserved_characters.jpg';
const String imageVariant = 'assets/normalFolder/3x/i have URI-reserved_characters.jpg';
final List<String> assets = <String>[
image,
imageVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
expect(manifest, hasLength(1));
expect(manifest[image], equals(<String>[image, imageVariant]));
});
sdk: flutter
flutter:
assets:
- assets/
'''
);
});
testWithoutContext('Only images in folders named with device pixel ratios (e.g. 2x, 3.0x) should be considered as variants of other images', () async {
const String image = 'assets/image.jpg';
const String image2xVariant = 'assets/2x/image.jpg';
const String imageNonVariant = 'assets/notAVariant/image.jpg';
group('AssetBundle asset variants (with Windows-style filepaths)', () {
late final Platform platform;
late final FileSystem fs;
final List<String> assets = <String>[
image,
image2xVariant,
imageNonVariant
];
setUp(() {
platform = FakePlatform(operatingSystem: 'windows');
fs = MemoryFileSystem.test(style: FileSystemStyle.windows);
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
fs.file('.packages').createSync();
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
assets:
- assets/
'''
);
});
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
testWithoutContext('Variant detection works with windows-style filepaths', () async {
const List<String> assets = <String>[
r'assets\foo.jpg',
r'assets\2x\foo.jpg',
r'assets\somewhereElse\bar.jpg',
r'assets\somewhereElse\2x\bar.jpg',
];
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
expect(manifest, hasLength(2));
expect(manifest[image], equals(<String>[image, image2xVariant]));
expect(manifest[imageNonVariant], equals(<String>[imageNonVariant]));
});
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
testWithoutContext('Asset directories are recursively searched for assets', () async {
const String topLevelImage = 'assets/image.jpg';
const String secondLevelImage = 'assets/folder/secondLevel.jpg';
const String secondLevel2xVariant = 'assets/folder/2x/secondLevel.jpg';
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final List<String> assets = <String>[
topLevelImage,
secondLevelImage,
secondLevel2xVariant
];
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
expect(manifest, hasLength(2));
expect(manifest['assets/foo.jpg'], equals(<String>['assets/foo.jpg', 'assets/2x/foo.jpg']));
expect(manifest['assets/somewhereElse/bar.jpg'], equals(<String>['assets/somewhereElse/bar.jpg', 'assets/somewhereElse/2x/bar.jpg']));
});
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
expect(manifest, hasLength(2));
expect(manifest[topLevelImage], equals(<String>[topLevelImage]));
expect(manifest[secondLevelImage], equals(<String>[secondLevelImage, secondLevel2xVariant]));
});
testWithoutContext('Asset paths should never be URI-encoded', () async {
const String image = 'assets/normalFolder/i have URI-reserved_characters.jpg';
const String imageVariant = 'assets/normalFolder/3x/i have URI-reserved_characters.jpg';
final List<String> assets = <String>[
image,
imageVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
expect(manifest, hasLength(1));
expect(manifest[image], equals(<String>[image, imageVariant]));
});
});
group('Current asset manifest (AssetManifest.bin)', () {
Future<String> extractAssetManifestFromBundleAsJson(ManifestAssetBundle bundle) async {
final List<int> manifestBytes = await bundle.entries['AssetManifest.bin']!.contentsAsBytes();
return json.encode(const StandardMessageCodec().decodeMessage(
ByteData.sublistView(Uint8List.fromList(manifestBytes))
));
}
group('AssetBundle asset variants (with Unix-style paths)', () {
late Platform platform;
late FileSystem fs;
group('AssetBundle asset variants (with Windows-style filepaths)', () {
late final Platform platform;
late final FileSystem fs;
setUp(() {
platform = FakePlatform();
fs = MemoryFileSystem.test();
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
setUp(() {
platform = FakePlatform(operatingSystem: 'windows');
fs = MemoryFileSystem.test(style: FileSystemStyle.windows);
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
fs.file('.packages').createSync();
fs.file('.packages').createSync();
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
sdk: flutter
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
assets:
- assets/
'''
);
});
testWithoutContext('Only images in folders named with device pixel ratios (e.g. 2x, 3.0x) should be considered as variants of other images', () async {
const String image = 'assets/image.jpg';
const String image2xVariant = 'assets/2x/image.jpg';
const String imageNonVariant = 'assets/notAVariant/image.jpg';
final List<String> assets = <String>[
image,
image2xVariant,
imageNonVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
const String expectedManifest = '{"$image":[{"asset":"$image2xVariant","dpr":2.0}],'
'"$imageNonVariant":[]}';
final String manifest = await extractAssetManifestFromBundleAsJson(bundle);
expect(manifest, equals(expectedManifest));
});
testWithoutContext('Asset directories are recursively searched for assets', () async {
const String topLevelImage = 'assets/image.jpg';
const String secondLevelImage = 'assets/folder/secondLevel.jpg';
const String secondLevel2xVariant = 'assets/folder/2x/secondLevel.jpg';
final List<String> assets = <String>[
topLevelImage,
secondLevelImage,
secondLevel2xVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
const String expectedManifest = '{'
'"$secondLevelImage":[{"asset":"$secondLevel2xVariant","dpr":2.0}],'
'"$topLevelImage":[]'
'}';
final String manifest = await extractAssetManifestFromBundleAsJson(bundle);
expect(manifest, equals(expectedManifest));
});
testWithoutContext('Asset paths should never be URI-encoded', () async {
const String image = 'assets/normalFolder/i have URI-reserved_characters.jpg';
const String imageVariant = 'assets/normalFolder/3x/i have URI-reserved_characters.jpg';
final List<String> assets = <String>[
image,
imageVariant
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
const String expectedManifest = '{"$image":[{"asset":"$imageVariant","dpr":3.0}]}';
final String manifest = await extractAssetManifestFromBundleAsJson(bundle);
expect(manifest, equals(expectedManifest));
});
sdk: flutter
flutter:
assets:
- assets/
'''
);
});
testWithoutContext('Variant detection works with windows-style filepaths', () async {
const List<String> assets = <String>[
r'assets\foo.jpg',
r'assets\2x\foo.jpg',
r'assets\somewhereElse\bar.jpg',
r'assets\somewhereElse\2x\bar.jpg',
];
group('AssetBundle asset variants (with Windows-style filepaths)', () {
late final Platform platform;
late final FileSystem fs;
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
setUp(() {
platform = FakePlatform(operatingSystem: 'windows');
fs = MemoryFileSystem.test(style: FileSystemStyle.windows);
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: platform,
fileSystem: fs,
userMessages: UserMessages()
);
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
fs.file('.packages').createSync();
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
fs.file('pubspec.yaml').writeAsStringSync(
'''
name: test
dependencies:
flutter:
sdk: flutter
flutter:
assets:
- assets/
'''
);
});
final Map<String, List<String>> manifest = await extractAssetManifestFromBundle(bundle);
testWithoutContext('Variant detection works with windows-style filepaths', () async {
const List<String> assets = <String>[
r'assets\foo.jpg',
r'assets\2x\foo.jpg',
r'assets\somewhereElse\bar.jpg',
r'assets\somewhereElse\2x\bar.jpg',
];
for (final String asset in assets) {
final File assetFile = fs.file(asset);
assetFile.createSync(recursive: true);
assetFile.writeAsStringSync(asset);
}
final ManifestAssetBundle bundle = ManifestAssetBundle(
logger: BufferLogger.test(),
fileSystem: fs,
platform: platform,
);
await bundle.build(
packagesPath: '.packages',
flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory),
);
const String expectedManifest = '{"assets/foo.jpg":[{"asset":"assets/2x/foo.jpg","dpr":2.0}],'
'"assets/somewhereElse/bar.jpg":[{"asset":"assets/somewhereElse/2x/bar.jpg","dpr":2.0}]}';
final String manifest = await extractAssetManifestFromBundleAsJson(bundle);
expect(manifest, equals(expectedManifest));
});
expect(manifest, hasLength(2));
expect(manifest['assets/foo.jpg'], equals(<String>['assets/foo.jpg', 'assets/2x/foo.jpg']));
expect(manifest['assets/somewhereElse/bar.jpg'], equals(<String>['assets/somewhereElse/bar.jpg', 'assets/somewhereElse/2x/bar.jpg']));
});
});
}