[flutter_tools] Deferred components build system (#76192)

This commit is contained in:
Gary Qian
2021-03-04 21:09:02 -05:00
committed by GitHub
parent faabc9ab46
commit ee41782732
33 changed files with 2008 additions and 245 deletions

View File

@@ -38,5 +38,7 @@ abstract class AndroidBuilder {
@required FlutterProject project,
@required AndroidBuildInfo androidBuildInfo,
@required String target,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
});
}

View File

@@ -30,10 +30,17 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
/// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit]
/// methods will exit the tool when this validator detects a recommended
/// change. This defaults to true.
DeferredComponentsGenSnapshotValidator(Environment env, {
DeferredComponentsGenSnapshotValidator(this.env, {
bool exitOnFail = true,
String title,
}) : super(env, exitOnFail: exitOnFail, title: title);
}) : super(env.projectDir, env.logger, exitOnFail: exitOnFail, title: title);
/// The build environment that should be used to find the input files to run
/// checks against.
///
/// The checks in this class are meant to be used as part of a build process,
/// so an environment should be available.
final Environment env;
// The key used to identify the metadata element as the loading unit id to
// deferred component mapping.
@@ -58,8 +65,8 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
/// Where loading unit 2 is included in componentA, loading unit 3 is included
/// in componentB, and loading unit 4 is included in componentC.
bool checkAppAndroidManifestComponentLoadingUnitMapping(List<DeferredComponent> components, List<LoadingUnit> generatedLoadingUnits) {
final Directory androidDir = env.projectDir.childDirectory('android');
inputs.add(env.projectDir.childFile('pubspec.yaml'));
final Directory androidDir = projectDir.childDirectory('android');
inputs.add(projectDir.childFile('pubspec.yaml'));
// We do not use the Xml package to handle the writing, as we do not want to
// erase any user applied formatting and comments. The changes can be
@@ -106,8 +113,10 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
mappingBuffer.write('$key:${mapping[key]},');
}
String encodedMapping = mappingBuffer.toString();
// remove trailing comma.
encodedMapping = encodedMapping.substring(0, encodedMapping.length - 1);
// remove trailing comma if any
if (encodedMapping.endsWith(',')) {
encodedMapping = encodedMapping.substring(0, encodedMapping.length - 1);
}
// Check for existing metadata entry and see if needs changes.
bool exists = false;
bool modified = false;
@@ -163,7 +172,7 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
/// considered new.
bool checkAgainstLoadingUnitsCache(
List<LoadingUnit> generatedLoadingUnits) {
final List<LoadingUnit> cachedLoadingUnits = _parseLodingUnitsCache(env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName));
final List<LoadingUnit> cachedLoadingUnits = _parseLodingUnitsCache(projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName));
loadingUnitComparisonResults = <String, dynamic>{};
final Set<LoadingUnit> unmatchedLoadingUnits = <LoadingUnit>{};
final List<LoadingUnit> newLoadingUnits = <LoadingUnit>[];
@@ -276,7 +285,7 @@ class DeferredComponentsGenSnapshotValidator extends DeferredComponentsValidator
/// deferred components.
void writeLoadingUnitsCache(List<LoadingUnit> generatedLoadingUnits) {
generatedLoadingUnits ??= <LoadingUnit>[];
final File cacheFile = env.projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName);
final File cacheFile = projectDir.childFile(DeferredComponentsValidator.kLoadingUnitsCacheFileName);
outputs.add(cacheFile);
ErrorHandlingFileSystem.deleteIfExists(cacheFile);
cacheFile.createSync(recursive: true);

View File

@@ -10,7 +10,7 @@ import 'package:xml/xml.dart';
import '../base/deferred_component.dart';
import '../base/error_handling_io.dart';
import '../base/file_system.dart';
import '../build_system/build_system.dart';
import '../base/logger.dart';
import '../globals.dart' as globals;
import '../project.dart';
import '../template.dart';
@@ -25,20 +25,18 @@ import 'deferred_components_validator.dart';
class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
/// Constructs a validator instance.
///
/// The [env] property is used to locate the project files that are checked.
///
/// The [templatesDir] parameter is optional. If null, the tool's default
/// templates directory will be used.
///
/// When [exitOnFail] is set to true, the [handleResults] and [attemptToolExit]
/// methods will exit the tool when this validator detects a recommended
/// change. This defaults to true.
DeferredComponentsPrebuildValidator(Environment env, {
DeferredComponentsPrebuildValidator(Directory projectDir, Logger logger, {
bool exitOnFail = true,
String title,
Directory templatesDir,
}) : _templatesDir = templatesDir,
super(env, exitOnFail: exitOnFail, title: title);
super(projectDir, logger, exitOnFail: exitOnFail, title: title);
final Directory _templatesDir;
@@ -56,7 +54,7 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
/// This method does not check if the contents of either of the files are
/// valid, as there are many ways that they can be validly configured.
Future<bool> checkAndroidDynamicFeature(List<DeferredComponent> components) async {
inputs.add(env.projectDir.childFile('pubspec.yaml'));
inputs.add(projectDir.childFile('pubspec.yaml'));
if (components == null || components.isEmpty) {
return false;
}
@@ -64,7 +62,8 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
for (final DeferredComponent component in components) {
final _DeferredComponentAndroidFiles androidFiles = _DeferredComponentAndroidFiles(
name: component.name,
env: env,
projectDir: projectDir,
logger: logger,
templatesDir: _templatesDir
);
if (!androidFiles.verifyFilesExist()) {
@@ -106,8 +105,8 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
/// The string element's name attribute should be the component name with
/// `Name` as a suffix, and the text contents should be the component name.
bool checkAndroidResourcesStrings(List<DeferredComponent> components) {
final Directory androidDir = env.projectDir.childDirectory('android');
inputs.add(env.projectDir.childFile('pubspec.yaml'));
final Directory androidDir = projectDir.childDirectory('android');
inputs.add(projectDir.childFile('pubspec.yaml'));
// Add component name mapping to strings.xml
final File stringRes = androidDir
@@ -202,7 +201,7 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
/// Deletes all files inside of the validator's output directory.
void clearOutputDir() {
final Directory dir = env.projectDir.childDirectory('build').childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory);
final Directory dir = projectDir.childDirectory('build').childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory);
ErrorHandlingFileSystem.deleteIfExists(dir, recursive: true);
}
}
@@ -212,16 +211,18 @@ class DeferredComponentsPrebuildValidator extends DeferredComponentsValidator {
class _DeferredComponentAndroidFiles {
_DeferredComponentAndroidFiles({
@required this.name,
@required this.env,
@required this.projectDir,
this.logger,
Directory templatesDir,
}) : _templatesDir = templatesDir;
// The name of the deferred component.
final String name;
final Environment env;
final Directory projectDir;
final Logger logger;
final Directory _templatesDir;
Directory get androidDir => env.projectDir.childDirectory('android');
Directory get androidDir => projectDir.childDirectory('android');
Directory get componentDir => androidDir.childDirectory(name);
File get androidManifestFile => componentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml');
@@ -250,18 +251,18 @@ class _DeferredComponentAndroidFiles {
Future<List<File>> _setupComponentFiles(Directory outputDir) async {
Template template;
if (_templatesDir != null) {
final Directory templateComponentDir = _templatesDir.childDirectory('module${env.fileSystem.path.separator}android${env.fileSystem.path.separator}deferred_component');
final Directory templateComponentDir = _templatesDir.childDirectory('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component');
template = Template(templateComponentDir, templateComponentDir, _templatesDir,
fileSystem: env.fileSystem,
fileSystem: globals.fs,
templateManifest: null,
logger: env.logger,
logger: logger,
templateRenderer: globals.templateRenderer,
);
} else {
template = await Template.fromName('module${env.fileSystem.path.separator}android${env.fileSystem.path.separator}deferred_component',
fileSystem: env.fileSystem,
template = await Template.fromName('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component',
fileSystem: globals.fs,
templateManifest: null,
logger: env.logger,
logger: logger,
templateRenderer: globals.templateRenderer,
);
}

View File

@@ -7,8 +7,8 @@
import '../base/common.dart';
import '../base/deferred_component.dart';
import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/terminal.dart';
import '../build_system/build_system.dart';
import '../globals.dart' as globals;
/// A class to configure and run deferred component setup verification checks
@@ -21,10 +21,10 @@ import '../globals.dart' as globals;
/// The results of each check are handled internally as they are not meant to
/// be run isolated.
abstract class DeferredComponentsValidator {
DeferredComponentsValidator(this.env, {
DeferredComponentsValidator(this.projectDir, this.logger, {
this.exitOnFail = true,
String title,
}) : outputDir = env.projectDir
}) : outputDir = projectDir
.childDirectory('build')
.childDirectory(kDeferredComponentsTempDirectory),
inputs = <File>[],
@@ -34,12 +34,9 @@ abstract class DeferredComponentsValidator {
modifiedFiles = <String>[],
invalidFiles = <String, String>{},
diffLines = <String>[];
/// The build environment that should be used to find the input files to run
/// checks against.
///
/// The checks in this class are meant to be used as part of a build process,
/// so an environment should be available.
final Environment env;
/// Logger to use for [displayResults] output.
final Logger logger;
/// When true, failed checks and tasks will result in [attemptToolExit]
/// triggering [throwToolExit].
@@ -54,6 +51,9 @@ abstract class DeferredComponentsValidator {
/// The title printed at the top of the results of [displayResults]
final String title;
/// The root directory of the flutter project.
final Directory projectDir;
/// The temporary directory that the validator writes recommended files into.
final Directory outputDir;
@@ -111,20 +111,20 @@ abstract class DeferredComponentsValidator {
/// All checks that are desired should be run before calling this method.
void displayResults() {
if (changesNeeded) {
env.logger.printStatus(_thickDivider);
env.logger.printStatus(title, indent: (_thickDivider.length - title.length) ~/ 2, emphasis: true);
env.logger.printStatus(_thickDivider);
logger.printStatus(_thickDivider);
logger.printStatus(title, indent: (_thickDivider.length - title.length) ~/ 2, emphasis: true);
logger.printStatus(_thickDivider);
// Log any file reading/existence errors.
if (invalidFiles.isNotEmpty) {
env.logger.printStatus('Errors checking the following files:\n', emphasis: true);
logger.printStatus('Errors checking the following files:\n', emphasis: true);
for (final String key in invalidFiles.keys) {
env.logger.printStatus(' - $key: ${invalidFiles[key]}\n');
logger.printStatus(' - $key: ${invalidFiles[key]}\n');
}
}
// Log diff file contents, with color highlighting
if (diffLines != null && diffLines.isNotEmpty) {
env.logger.printStatus('Diff between `android` and expected files:', emphasis: true);
env.logger.printStatus('');
logger.printStatus('Diff between `android` and expected files:', emphasis: true);
logger.printStatus('');
for (final String line in diffLines) {
// We only care about diffs in files that have
// counterparts.
@@ -137,62 +137,62 @@ abstract class DeferredComponentsValidator {
} else if (line.startsWith('-')) {
color = TerminalColor.red;
}
env.logger.printStatus(line, color: color);
logger.printStatus(line, color: color);
}
env.logger.printStatus('');
logger.printStatus('');
}
// Log any newly generated and modified files.
if (generatedFiles.isNotEmpty) {
env.logger.printStatus('Newly generated android files:', emphasis: true);
logger.printStatus('Newly generated android files:', emphasis: true);
for (final String filePath in generatedFiles) {
final String shortenedPath = filePath.substring(env.projectDir.parent.path.length + 1);
env.logger.printStatus(' - $shortenedPath', color: TerminalColor.grey);
final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1);
logger.printStatus(' - $shortenedPath', color: TerminalColor.grey);
}
env.logger.printStatus('');
logger.printStatus('');
}
if (modifiedFiles.isNotEmpty) {
env.logger.printStatus('Modified android files:', emphasis: true);
logger.printStatus('Modified android files:', emphasis: true);
for (final String filePath in modifiedFiles) {
final String shortenedPath = filePath.substring(env.projectDir.parent.path.length + 1);
env.logger.printStatus(' - $shortenedPath', color: TerminalColor.grey);
final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1);
logger.printStatus(' - $shortenedPath', color: TerminalColor.grey);
}
env.logger.printStatus('');
logger.printStatus('');
}
if (generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty) {
env.logger.printStatus('''
logger.printStatus('''
The above files have been placed into `build/$kDeferredComponentsTempDirectory`,
a temporary directory. The files should be reviewed and moved into the project's
`android` directory.''');
if (diffLines != null && diffLines.isNotEmpty && !globals.platform.isWindows) {
env.logger.printStatus(r'''
logger.printStatus(r'''
The recommended changes can be quickly applied by running:
$ patch -p0 < build/setup_deferred_components.diff
''');
}
env.logger.printStatus('$_thinDivider\n');
logger.printStatus('$_thinDivider\n');
}
// Log loading unit golden changes, if any.
if (loadingUnitComparisonResults != null) {
if ((loadingUnitComparisonResults['new'] as List<LoadingUnit>).isNotEmpty) {
env.logger.printStatus('New loading units were found:', emphasis: true);
logger.printStatus('New loading units were found:', emphasis: true);
for (final LoadingUnit unit in loadingUnitComparisonResults['new'] as List<LoadingUnit>) {
env.logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2);
logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2);
}
env.logger.printStatus('');
logger.printStatus('');
}
if ((loadingUnitComparisonResults['missing'] as Set<LoadingUnit>).isNotEmpty) {
env.logger.printStatus('Previously existing loading units no longer exist:', emphasis: true);
logger.printStatus('Previously existing loading units no longer exist:', emphasis: true);
for (final LoadingUnit unit in loadingUnitComparisonResults['missing'] as Set<LoadingUnit>) {
env.logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2);
logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2);
}
env.logger.printStatus('');
logger.printStatus('');
}
if (loadingUnitComparisonResults['match'] as bool) {
env.logger.printStatus('No change in generated loading units.\n');
logger.printStatus('No change in generated loading units.\n');
} else {
env.logger.printStatus('''
logger.printStatus('''
It is recommended to verify that the changed loading units are expected
and to update the `deferred-components` section in `pubspec.yaml` to
incorporate any changes. The full list of generated loading units can be
@@ -205,14 +205,14 @@ $_thinDivider\n''');
}
}
// TODO(garyq): Add link to web tutorial/guide once it is written.
env.logger.printStatus('''
Setup verification can be skipped by passing the `--no-verify-deferred-components`
logger.printStatus('''
Setup verification can be skipped by passing the `--no-validate-deferred-components`
flag, however, doing so may put your app at risk of not functioning even if the
build is successful.
$_thickDivider''');
return;
}
env.logger.printStatus('$title passed.');
logger.printStatus('$title passed.');
}
void attemptToolExit() {

View File

@@ -12,6 +12,7 @@ import 'package:xml/xml.dart';
import '../artifacts.dart';
import '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/deferred_component.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
@@ -242,6 +243,8 @@ class AndroidGradleBuilder implements AndroidBuilder {
@required FlutterProject project,
@required AndroidBuildInfo androidBuildInfo,
@required String target,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
}) async {
await buildGradleApp(
project: project,
@@ -249,6 +252,8 @@ class AndroidGradleBuilder implements AndroidBuilder {
target: target,
isBuildingBundle: true,
localGradleErrors: gradleErrors,
validateDeferredComponents: validateDeferredComponents,
deferredComponentsEnabled: deferredComponentsEnabled,
);
}
@@ -270,6 +275,8 @@ class AndroidGradleBuilder implements AndroidBuilder {
@required bool isBuildingBundle,
@required List<GradleHandledError> localGradleErrors,
bool shouldBuildPluginAsAar = false,
bool validateDeferredComponents = true,
bool deferredComponentsEnabled = false,
int retries = 1,
}) async {
assert(project != null);
@@ -355,8 +362,29 @@ class AndroidGradleBuilder implements AndroidBuilder {
if (target != null) {
command.add('-Ptarget=$target');
}
if (project.manifest.deferredComponents != null) {
if (deferredComponentsEnabled) {
command.add('-Pdeferred-components=true');
androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents');
}
// Pass in deferred components regardless of building split aot to satisfy
// android dynamic features registry in build.gradle.
final List<String> componentNames = <String>[];
for (final DeferredComponent component in project.manifest.deferredComponents) {
componentNames.add(component.name);
}
if (componentNames.isNotEmpty) {
command.add('-Pdeferred-component-names=${componentNames.join(',')}');
// Multi-apk applications cannot use shrinking. This is only relevant when using
// android dynamic feature modules.
_logger.printStatus(
'Shrinking has been disabled for this build due to deferred components. Shrinking is '
'not available for multi-apk applications. This limitation is expected to be removed '
'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow);
command.add('-Pshrink=false');
}
}
command.addAll(androidBuildInfo.buildInfo.toGradleConfig());
if (buildInfo.fileSystemRoots != null && buildInfo.fileSystemRoots.isNotEmpty) {
command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}');
}

View File

@@ -8,6 +8,7 @@ import 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'base/context.dart';
import 'base/deferred_component.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/platform.dart';
@@ -53,7 +54,8 @@ abstract class AssetBundleFactory {
@required Logger logger,
@required FileSystem fileSystem,
@required Platform platform,
}) => _ManifestAssetBundleFactory(logger: logger, fileSystem: fileSystem, platform: platform);
bool splitDeferredAssets = false,
}) => _ManifestAssetBundleFactory(logger: logger, fileSystem: fileSystem, platform: platform, splitDeferredAssets: splitDeferredAssets);
/// Creates a new [AssetBundle].
AssetBundle createBundle();
@@ -62,6 +64,10 @@ abstract class AssetBundleFactory {
abstract class AssetBundle {
Map<String, DevFSContent> get entries;
/// The files that were specified under the deferred components assets sections
/// in pubspec.
Map<String, Map<String, DevFSContent>> get deferredComponentsEntries;
/// Additional files that this bundle depends on that are not included in the
/// output result.
List<File> get additionalDependencies;
@@ -75,6 +81,7 @@ abstract class AssetBundle {
String manifestPath = defaultManifestPath,
String assetDirPath,
@required String packagesPath,
bool deferredComponentsEnabled = false,
});
}
@@ -83,16 +90,19 @@ class _ManifestAssetBundleFactory implements AssetBundleFactory {
@required Logger logger,
@required FileSystem fileSystem,
@required Platform platform,
bool splitDeferredAssets = false,
}) : _logger = logger,
_fileSystem = fileSystem,
_platform = platform;
_platform = platform,
_splitDeferredAssets = splitDeferredAssets;
final Logger _logger;
final FileSystem _fileSystem;
final Platform _platform;
final bool _splitDeferredAssets;
@override
AssetBundle createBundle() => ManifestAssetBundle(logger: _logger, fileSystem: _fileSystem, platform: _platform);
AssetBundle createBundle() => ManifestAssetBundle(logger: _logger, fileSystem: _fileSystem, platform: _platform, splitDeferredAssets: _splitDeferredAssets);
}
/// An asset bundle based on a pubspec.yaml file.
@@ -103,19 +113,25 @@ class ManifestAssetBundle implements AssetBundle {
@required Logger logger,
@required FileSystem fileSystem,
@required Platform platform,
bool splitDeferredAssets = false,
}) : _logger = logger,
_fileSystem = fileSystem,
_platform = platform,
_splitDeferredAssets = splitDeferredAssets,
_licenseCollector = LicenseCollector(fileSystem: fileSystem);
final Logger _logger;
final FileSystem _fileSystem;
final LicenseCollector _licenseCollector;
final Platform _platform;
final bool _splitDeferredAssets;
@override
final Map<String, DevFSContent> entries = <String, DevFSContent>{};
@override
final Map<String, Map<String, DevFSContent>> deferredComponentsEntries = <String, Map<String, DevFSContent>>{};
// If an asset corresponds to a wildcard directory, then it may have been
// updated without changes to the manifest. These are only tracked for
// the current project.
@@ -163,6 +179,7 @@ class ManifestAssetBundle implements AssetBundle {
String manifestPath = defaultManifestPath,
String assetDirPath,
@required String packagesPath,
bool deferredComponentsEnabled = false,
}) async {
assetDirPath ??= getAssetBuildDirectory();
FlutterProject flutterProject;
@@ -197,29 +214,49 @@ class ManifestAssetBundle implements AssetBundle {
// in the pubspec.yaml file's assets and font and sections. The
// value of each image asset is a list of resolution-specific "variants",
// see _AssetDirectoryCache.
final List<String> excludeDirs = <String>[
assetDirPath,
getBuildDirectory(),
if (flutterProject.ios.existsSync())
flutterProject.ios.hostAppRoot.path,
if (flutterProject.macos.existsSync())
flutterProject.macos.managedDirectory.path,
if (flutterProject.windows.existsSync())
flutterProject.windows.managedDirectory.path,
if (flutterProject.linux.existsSync())
flutterProject.linux.managedDirectory.path,
];
final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
packageConfig,
flutterManifest,
wildcardDirectories,
assetBasePath,
excludeDirs: <String>[
assetDirPath,
getBuildDirectory(),
if (flutterProject.ios.existsSync())
flutterProject.ios.hostAppRoot.path,
if (flutterProject.macos.existsSync())
flutterProject.macos.managedDirectory.path,
if (flutterProject.windows.existsSync())
flutterProject.windows.managedDirectory.path,
if (flutterProject.linux.existsSync())
flutterProject.linux.managedDirectory.path,
],
excludeDirs: excludeDirs,
);
if (assetVariants == null) {
return 1;
}
// Parse assets for deferred components.
final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = _parseDeferredComponentsAssets(
flutterManifest,
packageConfig,
assetBasePath,
wildcardDirectories,
flutterProject.directory,
excludeDirs: excludeDirs,
);
if (!_splitDeferredAssets || !deferredComponentsEnabled) {
// Include the assets in the regular set of assets if not using deferred
// components.
for (final String componentName in deferredComponentsAssetVariants.keys) {
assetVariants.addAll(deferredComponentsAssetVariants[componentName]);
}
deferredComponentsAssetVariants.clear();
deferredComponentsEntries.clear();
}
final bool includesMaterialFonts = flutterManifest.usesMaterialDesign;
final List<Map<String, dynamic>> fonts = _parseFonts(
flutterManifest,
@@ -314,6 +351,39 @@ class ManifestAssetBundle implements AssetBundle {
entries[variant.entryUri.path] ??= DevFSFileContent(variantFile);
}
}
// Save the contents of each deferred component image, image variant, and font
// asset in deferredComponentsEntries.
if (deferredComponentsAssetVariants != null) {
for (final String componentName in deferredComponentsAssetVariants.keys) {
deferredComponentsEntries[componentName] = <String, DevFSContent>{};
for (final _Asset asset in deferredComponentsAssetVariants[componentName].keys) {
final File assetFile = asset.lookupAssetFile(_fileSystem);
if (!assetFile.existsSync() && deferredComponentsAssetVariants[componentName][asset].isEmpty) {
_logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
_logger.printError('No file or variants found for $asset.\n');
if (asset.package != null) {
_logger.printError('This asset was included from package ${asset.package.name}.');
}
return 1;
}
// The file name for an asset's "main" entry is whatever appears in
// the pubspec.yaml file. The main entry's file must always exist for
// font assets. It need not exist for an image if resolution-specific
// variant files exist. An image's main entry is treated the same as a
// "1x" resolution variant and if both exist then the explicit 1x
// variant is preferred.
if (assetFile.existsSync()) {
assert(!deferredComponentsAssetVariants[componentName][asset].contains(asset));
deferredComponentsAssetVariants[componentName][asset].insert(0, asset);
}
for (final _Asset variant in deferredComponentsAssetVariants[componentName][asset]) {
final File variantFile = variant.lookupAssetFile(_fileSystem);
assert(variantFile.existsSync());
deferredComponentsEntries[componentName][variant.entryUri.path] ??= DevFSFileContent(variantFile);
}
}
}
}
final List<_Asset> materialAssets = <_Asset>[
if (flutterManifest.usesMaterialDesign)
..._getMaterialAssets(),
@@ -410,6 +480,50 @@ class ManifestAssetBundle implements AssetBundle {
];
}
Map<String, Map<_Asset, List<_Asset>>> _parseDeferredComponentsAssets(
FlutterManifest flutterManifest,
PackageConfig packageConfig,
String assetBasePath,
List<Uri> wildcardDirectories,
Directory projectDirectory, {
List<String> excludeDirs = const <String>[],
}) {
final List<DeferredComponent> components = flutterManifest.deferredComponents;
final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = <String, Map<_Asset, List<_Asset>>>{};
if (components == null) {
return deferredComponentsAssetVariants;
}
for (final DeferredComponent component in components) {
deferredComponentsAssetVariants[component.name] = <_Asset, List<_Asset>>{};
final _AssetDirectoryCache cache = _AssetDirectoryCache(<String>[], _fileSystem);
for (final Uri assetUri in component.assets) {
if (assetUri.path.endsWith('/')) {
wildcardDirectories.add(assetUri);
_parseAssetsFromFolder(
packageConfig,
flutterManifest,
assetBasePath,
cache,
deferredComponentsAssetVariants[component.name],
assetUri,
excludeDirs: excludeDirs,
);
} else {
_parseAssetFromFile(
packageConfig,
flutterManifest,
assetBasePath,
cache,
deferredComponentsAssetVariants[component.name],
assetUri,
excludeDirs: excludeDirs,
);
}
}
}
return deferredComponentsAssetVariants;
}
DevFSStringContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
final Map<String, List<String>> jsonObject = <String, List<String>>{};
final List<_Asset> assets = assetVariants.keys.toList()

View File

@@ -167,7 +167,7 @@ class AnsiTerminal implements Terminal {
static const String cyan = '\u001b[36m';
static const String magenta = '\u001b[35m';
static const String yellow = '\u001b[33m';
static const String grey = '\u001b[1;30m';
static const String grey = '\u001b[90m';
static const Map<TerminalColor, String> _colorMap = <TerminalColor, String>{
TerminalColor.red: red,

View File

@@ -25,10 +25,12 @@ class DepfileService {
/// Given an [depfile] File, write the depfile contents.
///
/// If either [inputs] or [outputs] is empty, ensures the file does not
/// exist.
void writeToFile(Depfile depfile, File output) {
if (depfile.inputs.isEmpty || depfile.outputs.isEmpty) {
/// If both [inputs] and [outputs] are empty, ensures the file does not
/// exist. This can be overriden with the [writeEmpty] parameter when
/// both static and runtime dependencies exist and it is not desired
/// to force a rerun due to no depfile.
void writeToFile(Depfile depfile, File output, {bool writeEmpty = false}) {
if (depfile.inputs.isEmpty && depfile.outputs.isEmpty && !writeEmpty) {
ErrorHandlingFileSystem.deleteIfExists(output);
return;
}

View File

@@ -146,7 +146,7 @@ class SourceVisitor implements ResolvedFiles {
throw InvalidPatternException(pattern);
}
if (!environment.fileSystem.directory(filePath).existsSync()) {
throw Exception('$filePath does not exist!');
environment.fileSystem.directory(filePath).createSync(recursive: true);
}
for (final FileSystemEntity entity in environment.fileSystem.directory(filePath).listSync()) {
final String filename = environment.fileSystem.path.basename(entity.path);

View File

@@ -10,6 +10,7 @@ import '../../base/deferred_component.dart';
import '../../base/file_system.dart';
import '../../build_info.dart';
import '../../globals.dart' as globals hide fs, artifacts, logger, processManager;
import '../../project.dart';
import '../build_system.dart';
import '../depfile.dart';
import '../exceptions.dart';
@@ -40,7 +41,6 @@ abstract class AndroidAssetBundle extends Target {
'flutter_assets.d',
];
@override
Future<void> build(Environment environment) async {
if (environment.defines[kBuildMode] == null) {
@@ -66,6 +66,7 @@ abstract class AndroidAssetBundle extends Target {
environment,
outputDirectory,
targetPlatform: TargetPlatform.android,
buildMode: buildMode,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,
@@ -173,7 +174,7 @@ class AndroidAot extends AotElfBase {
/// The selected build mode.
///
/// This is restricted to [BuildMode.profile] or [BuildMode.release].
/// Build mode is restricted to [BuildMode.profile] or [BuildMode.release] for AOT builds.
final BuildMode buildMode;
@override
@@ -193,6 +194,11 @@ class AndroidAot extends AotElfBase {
Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'),
];
@override
List<String> get depfiles => <String>[
'flutter_$name.d',
];
@override
List<Target> get dependencies => const <Target>[
KernelSnapshot(),
@@ -217,6 +223,12 @@ class AndroidAot extends AotElfBase {
output.createSync(recursive: true);
}
final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions);
final List<File> outputs = <File>[]; // outputs for the depfile
final String manifestPath = '${output.path}${globals.platform.pathSeparator}manifest.json';
if (environment.defines[kDeferredComponents] == 'true') {
extraGenSnapshotOptions.add('--loading_unit_manifest=$manifestPath');
outputs.add(environment.fileSystem.file(manifestPath));
}
final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true';
final String codeSizeDirectory = environment.defines[kCodeSizeDirectory];
@@ -245,6 +257,22 @@ class AndroidAot extends AotElfBase {
if (snapshotExitCode != 0) {
throw Exception('AOT snapshotter exited with code $snapshotExitCode');
}
if (environment.defines[kDeferredComponents] == 'true') {
// Parse the manifest for .so paths
final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(environment.fileSystem.file(manifestPath), environment.logger);
for (final LoadingUnit unit in loadingUnits) {
outputs.add(environment.fileSystem.file(unit.path));
}
}
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,
logger: environment.logger,
);
depfileService.writeToFile(
Depfile(<File>[], outputs),
environment.buildDir.childFile('flutter_$name.d'),
writeEmpty: true,
);
}
}
@@ -256,7 +284,7 @@ const AndroidAot androidArmRelease = AndroidAot(TargetPlatform.android_arm, Bui
const AndroidAot androidArm64Release = AndroidAot(TargetPlatform.android_arm64, BuildMode.release);
const AndroidAot androidx64Release = AndroidAot(TargetPlatform.android_x64, BuildMode.release);
/// A rule paired with [AndroidAot] that copies the produced so files into the output directory.
/// A rule paired with [AndroidAot] that copies the produced so file and manifest.json (if present) into the output directory.
class AndroidAotBundle extends Target {
/// Create an [AndroidAotBundle] implementation for a given [targetPlatform] and [buildMode].
const AndroidAotBundle(this.dependency);
@@ -274,9 +302,16 @@ class AndroidAotBundle extends Target {
String get name => 'android_aot_bundle_${getNameForBuildMode(dependency.buildMode)}_'
'${getNameForTargetPlatform(dependency.targetPlatform)}';
TargetPlatform get targetPlatform => dependency.targetPlatform;
/// The selected build mode.
///
/// This is restricted to [BuildMode.profile] or [BuildMode.release].
BuildMode get buildMode => dependency.buildMode;
@override
List<Source> get inputs => <Source>[
Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'),
Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'),
];
// flutter.gradle has been updated to correctly consume it.
@@ -285,6 +320,11 @@ class AndroidAotBundle extends Target {
Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'),
];
@override
List<String> get depfiles => <String>[
'flutter_$name.d',
];
@override
List<Target> get dependencies => <Target>[
dependency,
@@ -293,25 +333,134 @@ class AndroidAotBundle extends Target {
@override
Future<void> build(Environment environment) async {
final File outputFile = environment.buildDir
.childDirectory(_androidAbiName)
.childFile('app.so');
final Directory buildDir = environment.buildDir.childDirectory(_androidAbiName);
final Directory outputDirectory = environment.outputDir
.childDirectory(_androidAbiName);
if (!outputDirectory.existsSync()) {
outputDirectory.createSync(recursive: true);
}
outputFile.copySync(outputDirectory.childFile('app.so').path);
final File outputLibFile = buildDir.childFile('app.so');
outputLibFile.copySync(outputDirectory.childFile('app.so').path);
final List<File> inputs = <File>[];
final List<File> outputs = <File>[];
final File manifestFile = buildDir.childFile('manifest.json');
if (manifestFile.existsSync()) {
final File destinationFile = outputDirectory.childFile('manifest.json');
manifestFile.copySync(destinationFile.path);
inputs.add(manifestFile);
outputs.add(destinationFile);
}
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,
logger: environment.logger,
);
depfileService.writeToFile(
Depfile(inputs, outputs),
environment.buildDir.childFile('flutter_$name.d'),
writeEmpty: true,
);
}
}
// AndroidBundleAot instances.
const Target androidArmProfileBundle = AndroidAotBundle(androidArmProfile);
const Target androidArm64ProfileBundle = AndroidAotBundle(androidArm64Profile);
const Target androidx64ProfileBundle = AndroidAotBundle(androidx64Profile);
const Target androidArmReleaseBundle = AndroidAotBundle(androidArmRelease);
const Target androidArm64ReleaseBundle = AndroidAotBundle(androidArm64Release);
const Target androidx64ReleaseBundle = AndroidAotBundle(androidx64Release);
const AndroidAotBundle androidArmProfileBundle = AndroidAotBundle(androidArmProfile);
const AndroidAotBundle androidArm64ProfileBundle = AndroidAotBundle(androidArm64Profile);
const AndroidAotBundle androidx64ProfileBundle = AndroidAotBundle(androidx64Profile);
const AndroidAotBundle androidArmReleaseBundle = AndroidAotBundle(androidArmRelease);
const AndroidAotBundle androidArm64ReleaseBundle = AndroidAotBundle(androidArm64Release);
const AndroidAotBundle androidx64ReleaseBundle = AndroidAotBundle(androidx64Release);
// Rule that copies split aot library files to the intermediate dirs of each deferred component.
class AndroidAotDeferredComponentsBundle extends Target {
/// Create an [AndroidAotDeferredComponentsBundle] implementation for a given [targetPlatform] and [buildMode].
///
/// If [components] is not provided, it will be read from the pubspec.yaml manifest.
AndroidAotDeferredComponentsBundle(this.dependency, {List<DeferredComponent> components}) : _components = components;
/// The [AndroidAotBundle] instance this bundle rule depends on.
final AndroidAotBundle dependency;
List<DeferredComponent> _components;
/// The name of the produced Android ABI.
String get _androidAbiName {
return getNameForAndroidArch(
getAndroidArchForName(getNameForTargetPlatform(dependency.targetPlatform)));
}
@override
String get name => 'android_aot_deferred_components_bundle_${getNameForBuildMode(dependency.buildMode)}_'
'${getNameForTargetPlatform(dependency.targetPlatform)}';
TargetPlatform get targetPlatform => dependency.targetPlatform;
@override
List<Source> get inputs => <Source>[
// Tracking app.so is enough to invalidate the dynamically named
// loading unit libs as changes to loading units guarantee
// changes to app.so as well. This task does not actually
// copy app.so.
Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'),
const Source.pattern('{PROJECT_DIR}/pubspec.yaml'),
];
@override
List<Source> get outputs => const <Source>[];
@override
List<String> get depfiles => <String>[
'flutter_$name.d',
];
@override
List<Target> get dependencies => <Target>[
dependency,
];
@override
Future<void> build(Environment environment) async {
_components ??= FlutterProject.current().manifest.deferredComponents ?? <DeferredComponent>[];
final List<String> abis = <String>[_androidAbiName];
final List<LoadingUnit> generatedLoadingUnits = LoadingUnit.parseGeneratedLoadingUnits(environment.outputDir, environment.logger, abis: abis);
for (final DeferredComponent component in _components) {
component.assignLoadingUnits(generatedLoadingUnits);
}
final Depfile libDepfile = copyDeferredComponentSoFiles(environment, _components, generatedLoadingUnits, environment.projectDir.childDirectory('build'), abis, dependency.buildMode);
final File manifestFile = environment.outputDir.childDirectory(_androidAbiName).childFile('manifest.json');
if (manifestFile.existsSync()) {
libDepfile.inputs.add(manifestFile);
}
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,
logger: environment.logger,
);
depfileService.writeToFile(
libDepfile,
environment.buildDir.childFile('flutter_$name.d'),
writeEmpty: true,
);
}
}
Target androidArmProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmProfileBundle);
Target androidArm64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ProfileBundle);
Target androidx64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ProfileBundle);
Target androidArmReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmReleaseBundle);
Target androidArm64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ReleaseBundle);
Target androidx64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ReleaseBundle);
/// A set of all target names that build deferred component apps.
Set<String> deferredComponentsTargets = <String>{
androidArmProfileDeferredComponentsBundle.name,
androidArm64ProfileDeferredComponentsBundle.name,
androidx64ProfileDeferredComponentsBundle.name,
androidArmReleaseDeferredComponentsBundle.name,
androidArm64ReleaseDeferredComponentsBundle.name,
androidx64ReleaseDeferredComponentsBundle.name,
};
/// Utility method to copy and rename the required .so shared libs from the build output
/// to the correct component intermediate directory.

View File

@@ -34,6 +34,7 @@ const String kBundleSkSLPath = 'BundleSkSLPath';
Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
Map<String, DevFSContent> additionalContent,
@required TargetPlatform targetPlatform,
BuildMode buildMode,
}) async {
// Check for an SkSL bundle.
final String shaderBundlePath = environment.inputs[kBundleSkSLPath];
@@ -51,11 +52,13 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
logger: environment.logger,
fileSystem: environment.fileSystem,
platform: globals.platform,
splitDeferredAssets: buildMode != BuildMode.debug && buildMode != BuildMode.jitRelease,
).createBundle();
final int resultCode = await assetBundle.build(
manifestPath: pubspecFile.path,
packagesPath: environment.projectDir.childFile('.packages').path,
assetDirPath: null,
deferredComponentsEnabled: environment.defines[kDeferredComponents] == 'true',
);
if (resultCode != 0) {
throw Exception('Failed to bundle asset files.');
@@ -114,6 +117,56 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory, {
resource.release();
}
}));
// Copy deferred components assets only for release or profile builds.
// The assets are included in assetBundle.entries as a normal asset when
// building as debug.
if (environment.defines[kDeferredComponents] == 'true') {
await Future.wait<void>(
assetBundle.deferredComponentsEntries.entries.map<Future<void>>((MapEntry<String, Map<String, DevFSContent>> componentEntries) async {
final Directory componentOutputDir =
environment.projectDir
.childDirectory('build')
.childDirectory(componentEntries.key)
.childDirectory('intermediates')
.childDirectory('flutter');
await Future.wait<void>(
componentEntries.value.entries.map<Future<void>>((MapEntry<String, DevFSContent> entry) async {
final PoolResource resource = await pool.request();
try {
// This will result in strange looking files, for example files with `/`
// on Windows or files that end up getting URI encoded such as `#.ext`
// to `%23.ext`. However, we have to keep it this way since the
// platform channels in the framework will URI encode these values,
// and the native APIs will look for files this way.
// If deferred components are disabled, then copy assets to regular location.
final File file = environment.defines[kDeferredComponents] == 'true'
? environment.fileSystem.file(
environment.fileSystem.path.join(componentOutputDir.path, buildMode.name, 'deferred_assets', 'flutter_assets', entry.key))
: environment.fileSystem.file(
environment.fileSystem.path.join(outputDirectory.path, entry.key));
outputs.add(file);
file.parent.createSync(recursive: true);
final DevFSContent content = entry.value;
if (content is DevFSFileContent && content.file is File) {
inputs.add(content.file as File);
if (!await iconTreeShaker.subsetFont(
input: content.file as File,
outputPath: file.path,
relativePath: entry.key,
)) {
await (content.file as File).copy(file.path);
}
} else {
await file.writeAsBytes(await entry.value.contentsAsBytes());
}
} finally {
resource.release();
}
}));
}));
}
final Depfile depfile = Depfile(inputs + assetBundle.additionalDependencies, outputs);
if (shaderBundlePath != null) {
final File skSLBundleFile = environment.fileSystem

View File

@@ -45,9 +45,9 @@ const String kExtraFrontEndOptions = 'ExtraFrontEndOptions';
/// This is expected to be a comma separated list of strings.
const String kExtraGenSnapshotOptions = 'ExtraGenSnapshotOptions';
/// Whether the app should run gen_snapshot as a split aot build for deferred
/// Whether the build should run gen_snapshot as a split aot build for deferred
/// components.
const String kSplitAot = 'SplitAot';
const String kDeferredComponents = 'DeferredComponents';
/// Whether to strip source code information out of release builds and where to save it.
const String kSplitDebugInfo = 'SplitDebugInfo';
@@ -131,6 +131,7 @@ class CopyFlutterBundle extends Target {
environment,
environment.outputDir,
targetPlatform: TargetPlatform.android,
buildMode: buildMode,
);
final DepfileService depfileService = DepfileService(
fileSystem: environment.fileSystem,

View File

@@ -8,25 +8,26 @@ import 'package:meta/meta.dart';
import '../../android/deferred_components_gen_snapshot_validator.dart';
import '../../base/deferred_component.dart';
import '../../build_info.dart';
import '../../project.dart';
import '../build_system.dart';
import '../depfile.dart';
import 'android.dart';
/// Creates a [DeferredComponentsGenSnapshotValidator], runs the checks, and displays the validator
/// output to the developer if changes are recommended.
class DeferredComponentsGenSnapshotValidatorTarget extends Target {
/// Create an [AndroidAotDeferredComponentsBundle] implementation for a given [targetPlatform] and [buildMode].
DeferredComponentsGenSnapshotValidatorTarget({
@required this.dependency,
@required this.abis,
@required this.deferredComponentsDependencies,
@required this.nonDeferredComponentsDependencies,
this.title,
this.exitOnFail = true,
String name = 'deferred_components_setup_validator',
}) : _name = name;
});
/// The [AndroidAotDeferredComponentsBundle] derived target instances this rule depends on packed
/// as a [CompositeTarget].
final CompositeTarget dependency;
/// The [AndroidAotDeferredComponentsBundle] derived target instances this rule depends on.
final List<AndroidAotDeferredComponentsBundle> deferredComponentsDependencies;
final List<Target> nonDeferredComponentsDependencies;
/// The title of the [DeferredComponentsGenSnapshotValidator] that is
/// displayed to the developer when logging results.
@@ -37,11 +38,20 @@ class DeferredComponentsGenSnapshotValidatorTarget extends Target {
final bool exitOnFail;
/// The abis to validate.
final List<String> abis;
List<String> get _abis {
final List<String> abis = <String>[];
for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies) {
if (deferredComponentsTargets.contains(target.name)) {
abis.add(
getNameForAndroidArch(getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)))
);
}
}
return abis;
}
@override
String get name => _name;
final String _name;
String get name => 'deferred_components_gen_snapshot_validator';
@override
List<Source> get inputs => const <Source>[];
@@ -55,7 +65,11 @@ class DeferredComponentsGenSnapshotValidatorTarget extends Target {
];
@override
List<Target> get dependencies => dependency == null ? <Target>[] : <Target>[dependency];
List<Target> get dependencies {
final List<Target> deps = <Target>[CompositeTarget(deferredComponentsDependencies)];
deps.addAll(nonDeferredComponentsDependencies);
return deps;
}
@visibleForTesting
DeferredComponentsGenSnapshotValidator validator;
@@ -75,7 +89,7 @@ class DeferredComponentsGenSnapshotValidatorTarget extends Target {
final List<LoadingUnit> generatedLoadingUnits = LoadingUnit.parseGeneratedLoadingUnits(
environment.outputDir,
environment.logger,
abis: abis
abis: _abis
);
validator

View File

@@ -14,6 +14,7 @@ import '../build_system/depfile.dart';
import '../build_system/targets/android.dart';
import '../build_system/targets/assets.dart';
import '../build_system/targets/common.dart';
import '../build_system/targets/deferred_components.dart';
import '../build_system/targets/ios.dart';
import '../build_system/targets/linux.dart';
import '../build_system/targets/macos.dart';
@@ -27,34 +28,34 @@ import '../reporting/reporting.dart';
import '../runner/flutter_command.dart';
/// All currently implemented targets.
const List<Target> _kDefaultTargets = <Target>[
List<Target> _kDefaultTargets = <Target>[
// Shared targets
CopyAssets(),
KernelSnapshot(),
AotElfProfile(TargetPlatform.android_arm),
AotElfRelease(TargetPlatform.android_arm),
AotAssemblyProfile(),
AotAssemblyRelease(),
const CopyAssets(),
const KernelSnapshot(),
const AotElfProfile(TargetPlatform.android_arm),
const AotElfRelease(TargetPlatform.android_arm),
const AotAssemblyProfile(),
const AotAssemblyRelease(),
// macOS targets
DebugMacOSFramework(),
DebugMacOSBundleFlutterAssets(),
ProfileMacOSBundleFlutterAssets(),
ReleaseMacOSBundleFlutterAssets(),
const DebugMacOSFramework(),
const DebugMacOSBundleFlutterAssets(),
const ProfileMacOSBundleFlutterAssets(),
const ReleaseMacOSBundleFlutterAssets(),
// Linux targets
DebugBundleLinuxAssets(TargetPlatform.linux_x64),
DebugBundleLinuxAssets(TargetPlatform.linux_arm64),
ProfileBundleLinuxAssets(TargetPlatform.linux_x64),
ProfileBundleLinuxAssets(TargetPlatform.linux_arm64),
ReleaseBundleLinuxAssets(TargetPlatform.linux_x64),
ReleaseBundleLinuxAssets(TargetPlatform.linux_arm64),
const DebugBundleLinuxAssets(TargetPlatform.linux_x64),
const DebugBundleLinuxAssets(TargetPlatform.linux_arm64),
const ProfileBundleLinuxAssets(TargetPlatform.linux_x64),
const ProfileBundleLinuxAssets(TargetPlatform.linux_arm64),
const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64),
const ReleaseBundleLinuxAssets(TargetPlatform.linux_arm64),
// Web targets
WebServiceWorker(),
ReleaseAndroidApplication(),
const WebServiceWorker(),
const ReleaseAndroidApplication(),
// This is a one-off rule for bundle and aot compat.
CopyFlutterBundle(),
const CopyFlutterBundle(),
// Android targets,
DebugAndroidApplication(),
ProfileAndroidApplication(),
const DebugAndroidApplication(),
const ProfileAndroidApplication(),
// Android ABI specific AOT rules.
androidArmProfileBundle,
androidArm64ProfileBundle,
@@ -62,15 +63,22 @@ const List<Target> _kDefaultTargets = <Target>[
androidArmReleaseBundle,
androidArm64ReleaseBundle,
androidx64ReleaseBundle,
// Deferred component enabled AOT rules
androidArmProfileDeferredComponentsBundle,
androidArm64ProfileDeferredComponentsBundle,
androidx64ProfileDeferredComponentsBundle,
androidArmReleaseDeferredComponentsBundle,
androidArm64ReleaseDeferredComponentsBundle,
androidx64ReleaseDeferredComponentsBundle,
// iOS targets
DebugIosApplicationBundle(),
ProfileIosApplicationBundle(),
ReleaseIosApplicationBundle(),
const DebugIosApplicationBundle(),
const ProfileIosApplicationBundle(),
const ReleaseIosApplicationBundle(),
// Windows targets
UnpackWindows(),
DebugBundleWindowsAssets(),
ProfileBundleWindowsAssets(),
ReleaseBundleWindowsAssets(),
const UnpackWindows(),
const DebugBundleWindowsAssets(),
const ProfileBundleWindowsAssets(),
const ReleaseBundleWindowsAssets(),
];
// TODO(ianh): https://github.com/dart-lang/args/issues/181 will allow us to remove useLegacyNames
@@ -171,6 +179,24 @@ class AssembleCommand extends FlutterCommand {
return results;
}
bool isDeferredComponentsTargets() {
for (final String targetName in argResults.rest) {
if (deferredComponentsTargets.contains(targetName)) {
return true;
}
}
return false;
}
bool isDebug() {
for (final String targetName in argResults.rest) {
if (targetName.contains('debug')) {
return true;
}
}
return false;
}
/// The environmental configuration for a build invocation.
Environment createEnvironment() {
final FlutterProject flutterProject = FlutterProject.current();
@@ -221,6 +247,10 @@ class AssembleCommand extends FlutterCommand {
if (argResults.wasParsed(useLegacyNames ? kDartDefines : FlutterOptions.kDartDefinesOption)) {
results[kDartDefines] = (argResults[useLegacyNames ? kDartDefines : FlutterOptions.kDartDefinesOption] as List<String>).join(',');
}
results[kDeferredComponents] = 'false';
if (FlutterProject.current().manifest.deferredComponents != null && isDeferredComponentsTargets() && !isDebug()) {
results[kDeferredComponents] = 'true';
}
if (argResults.wasParsed(useLegacyNames ? kExtraFrontEndOptions : FlutterOptions.kExtraFrontEndOptions)) {
results[kExtraFrontEndOptions] = (argResults[useLegacyNames ? kExtraFrontEndOptions : FlutterOptions.kExtraFrontEndOptions] as List<String>).join(',');
}
@@ -229,11 +259,37 @@ class AssembleCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
final Environment env = createEnvironment();
final List<Target> targets = createTargets();
final Target target = targets.length == 1 ? targets.single : CompositeTarget(targets);
final List<Target> nonDeferredTargets = <Target>[];
final List<Target> deferredTargets = <AndroidAotDeferredComponentsBundle>[];
for (final Target target in targets) {
if (deferredComponentsTargets.contains(target.name)) {
deferredTargets.add(target);
} else {
nonDeferredTargets.add(target);
}
}
Target target;
final List<String> decodedDefines = decodeDartDefines(env.defines, kDartDefines);
if (FlutterProject.current().manifest.deferredComponents != null
&& decodedDefines.contains('validate-deferred-components=true')
&& deferredTargets.isNotEmpty
&& !isDebug()) {
// Add deferred components validation target that require loading units.
target = DeferredComponentsGenSnapshotValidatorTarget(
deferredComponentsDependencies: deferredTargets.cast<AndroidAotDeferredComponentsBundle>(),
nonDeferredComponentsDependencies: nonDeferredTargets,
title: 'Deferred components gen_snapshot validation',
);
} else if (targets.length > 1) {
target = CompositeTarget(targets);
} else if (targets.isNotEmpty) {
target = targets.single;
}
final BuildResult result = await _buildSystem.build(
target,
createEnvironment(),
env,
buildSystemConfig: BuildSystemConfig(
resourcePoolSize: argResults.wasParsed('resource-pool-size')
? int.tryParse(stringArg('resource-pool-size'))
@@ -251,6 +307,7 @@ class AssembleCommand extends FlutterCommand {
throwToolExit('');
}
globals.printTrace('build succeeded.');
if (argResults.wasParsed('build-inputs')) {
writeListIfChanged(result.inputFiles, stringArg('build-inputs'));
}

View File

@@ -6,7 +6,10 @@
import '../android/android_builder.dart';
import '../android/build_validation.dart';
import '../android/deferred_components_prebuild_validator.dart';
import '../android/gradle_utils.dart';
import '../base/deferred_component.dart';
import '../base/file_system.dart';
import '../build_info.dart';
import '../cache.dart';
import '../globals.dart' as globals;
@@ -37,11 +40,30 @@ class BuildAppBundleCommand extends BuildSubCommand {
usesAnalyzeSizeFlag();
addAndroidSpecificBuildOptions(hide: !verboseHelp);
argParser.addMultiOption('target-platform',
splitCommas: true,
defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'],
allowed: <String>['android-arm', 'android-arm64', 'android-x64'],
help: 'The target platform for which the app is compiled.',
);
splitCommas: true,
defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'],
allowed: <String>['android-arm', 'android-arm64', 'android-x64'],
help: 'The target platform for which the app is compiled.',
);
argParser.addFlag('deferred-components',
negatable: true,
defaultsTo: true,
help: 'Setting to false disables building with deferred components. All deferred code '
'will be compiled into the base app, and assets act as if they were defined under'
' the regular assets section in pubspec.yaml. This flag has no effect on '
'non-deferred components apps.',
);
argParser.addFlag('validate-deferred-components',
negatable: true,
defaultsTo: true,
help: 'When enabled, deferred component apps will fail to build if setup problems are '
'detected that would prevent deferred components from functioning properly. The '
'tooling also provides guidance on how to set up the project files to pass this '
'verification. Disabling setup verification will always attempt to fully build '
'the app regardless of any problems detected. Builds that are part of CI testing '
'and advanced users with custom deferred components implementations should disable '
'setup verification. This flag has no effect on non-deferred components apps.',
);
}
@override
@@ -84,15 +106,49 @@ class BuildAppBundleCommand extends BuildSubCommand {
if (globals.androidSdk == null) {
exitWithNoSdkMessage();
}
final AndroidBuildInfo androidBuildInfo = AndroidBuildInfo(await getBuildInfo(),
targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName),
);
// Do all setup verification that doesn't involve loading units. Checks that
// require generated loading units are done after gen_snapshot in assemble.
if (FlutterProject.current().manifest.deferredComponents != null && boolArg('deferred-components') && boolArg('validate-deferred-components') && !boolArg('debug')) {
final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator(
FlutterProject.current().directory,
globals.logger,
title: 'Deferred components prebuild validation',
exitOnFail: true,
);
validator.clearOutputDir();
await validator.checkAndroidDynamicFeature(FlutterProject.current().manifest.deferredComponents);
validator.checkAndroidResourcesStrings(FlutterProject.current().manifest.deferredComponents);
validator.handleResults();
// Delete intermediates libs dir for components to resolve mismatching
// abis supported by base and dynamic feature modules.
for (final DeferredComponent component in FlutterProject.current().manifest.deferredComponents) {
final Directory deferredLibsIntermediate = FlutterProject.current().directory
.childDirectory('build')
.childDirectory(component.name)
.childDirectory('intermediates')
.childDirectory('flutter')
.childDirectory(androidBuildInfo.buildInfo.mode.name)
.childDirectory('deferred_libs');
if (deferredLibsIntermediate.existsSync()) {
deferredLibsIntermediate.deleteSync(recursive: true);
}
}
}
validateBuild(androidBuildInfo);
displayNullSafetyMode(androidBuildInfo.buildInfo);
await androidBuilder.buildAab(
project: FlutterProject.current(),
target: targetFile,
androidBuildInfo: androidBuildInfo,
validateDeferredComponents: boolArg('validate-deferred-components'),
deferredComponentsEnabled: boolArg('deferred-components') && !boolArg('debug'),
);
return FlutterCommandResult.success();
}

View File

@@ -120,6 +120,7 @@ class FlutterOptions {
static const String kAnalyzeSize = 'analyze-size';
static const String kNullAssertions = 'null-assertions';
static const String kAndroidGradleDaemon = 'android-gradle-daemon';
static const String kDeferredComponents = 'deferred-components';
}
abstract class FlutterCommand extends Command<void> {