Enable asset transformation for flutter build for iOS, Android, Windows, MacOS, Linux, and web (also flutter run without hot reload support) (#143815)

See title. These are are the platforms that use the `CopyAssets` `Target` as part of their build target.

Partial implementation of https://github.com/flutter/flutter/issues/143348.
This commit is contained in:
Andrew Kolos
2024-02-23 14:48:08 -08:00
committed by GitHub
parent 15f8ef71d9
commit 4e814a5f3c
8 changed files with 767 additions and 10 deletions

View File

@@ -0,0 +1,373 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/args.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/build_system/tools/asset_transformer.dart';
import 'package:flutter_tools/src/flutter_manifest.dart';
import '../../../src/common.dart';
import '../../../src/fake_process_manager.dart';
void main() {
testWithoutContext('Invokes dart properly', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final BufferLogger logger = BufferLogger.test();
final Artifacts artifacts = Artifacts.test();
final File asset = fileSystem.file('asset.txt')..createSync()..writeAsStringSync('hello world');
const String outputPath = 'output.txt';
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
artifacts.getArtifactPath(Artifact.engineDartBinary),
'run',
'my_copy_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput0.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput1.txt',
'-f',
'--my_option',
'my_option_value',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output')
..addFlag('foo', abbr: 'f')
..addOption('my_option'))
.parse(args);
fileSystem.file(parsedArgs['input']).copySync(parsedArgs['output'] as String);
},
),
]);
final AssetTransformer transformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: artifacts.getArtifactPath(Artifact.engineDartBinary),
);
final AssetTransformationFailure? transformationFailure = await transformer.transformAsset(
asset: asset,
outputPath: outputPath,
workingDirectory: fileSystem.currentDirectory.path,
transformerEntries: <AssetTransformerEntry>[
const AssetTransformerEntry(
package: 'my_copy_transformer',
args: <String>[
'-f',
'--my_option',
'my_option_value',
],
)
],
);
expect(transformationFailure, isNull, reason: logger.errorText);
expect(processManager, hasNoRemainingExpectations);
expect(fileSystem.file(outputPath).readAsStringSync(), 'hello world');
});
testWithoutContext('logs useful error information when transformation process returns a nonzero exit code', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Artifacts artifacts = Artifacts.test();
final File asset = fileSystem.file('asset.txt')..createSync();
const String outputPath = 'output.txt';
final String dartBinaryPath = artifacts.getArtifactPath(Artifact.engineDartBinary);
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_copy_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput0.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput1.txt',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output'))
.parse(args);
fileSystem.file(parsedArgs['input']).copySync(parsedArgs['output'] as String);
},
exitCode: 1,
stdout: 'Beginning transformation',
stderr: 'Something went wrong',
),
]);
final AssetTransformer transformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: dartBinaryPath,
);
final AssetTransformationFailure? failure = await transformer.transformAsset(
asset: asset,
outputPath: outputPath,
workingDirectory: fileSystem.currentDirectory.path,
transformerEntries: <AssetTransformerEntry>[
const AssetTransformerEntry(
package: 'my_copy_transformer',
args: <String>[],
)
],
);
expect(asset, exists);
expect(processManager, hasNoRemainingExpectations);
expect(failure, isNotNull);
expect(failure!.message,
'''
User-defined transformation of asset "asset.txt" failed.
Transformer process terminated with non-zero exit code: 1
Transformer package: my_copy_transformer
Full command: $dartBinaryPath run my_copy_transformer --input=/.tmp_rand0/asset.txt-transformOutput0.txt --output=/.tmp_rand0/asset.txt-transformOutput1.txt
stdout:
Beginning transformation
stderr:
Something went wrong''');
});
testWithoutContext('prints error message when the transformer does not produce an output file', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Artifacts artifacts = Artifacts.test();
final File asset = fileSystem.file('asset.txt')..createSync();
const String outputPath = 'output.txt';
final String dartBinaryPath = artifacts.getArtifactPath(Artifact.engineDartBinary);
final FakeProcessManager processManager =
FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput0.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput1.txt',
],
onRun: (_) {
// Do nothing.
},
stderr: 'Transformation failed, but I forgot to exit with a non-zero code.'
),
]);
final AssetTransformer transformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: dartBinaryPath,
);
final AssetTransformationFailure? failure = await transformer.transformAsset(
asset: asset,
outputPath: outputPath,
workingDirectory: fileSystem.currentDirectory.path,
transformerEntries: <AssetTransformerEntry>[
const AssetTransformerEntry(
package: 'my_transformer',
args: <String>[],
)
],
);
expect(processManager, hasNoRemainingExpectations);
expect(failure, isNotNull);
expect(failure!.message,
'''
User-defined transformation of asset "asset.txt" failed.
Asset transformer my_transformer did not produce an output file.
Input file provided to transformer: "/.tmp_rand0/asset.txt-transformOutput0.txt"
Expected output file at: "/.tmp_rand0/asset.txt-transformOutput1.txt"
Full command: $dartBinaryPath run my_transformer --input=/.tmp_rand0/asset.txt-transformOutput0.txt --output=/.tmp_rand0/asset.txt-transformOutput1.txt
stdout:
stderr:
Transformation failed, but I forgot to exit with a non-zero code.'''
);
});
testWithoutContext('correctly chains transformations when there are multiple of them', () async {
final FileSystem fileSystem = MemoryFileSystem.test();
final Artifacts artifacts = Artifacts.test();
final File asset = fileSystem.file('asset.txt')
..createSync()
..writeAsStringSync('ABC');
const String outputPath = 'output.txt';
final String dartBinaryPath = artifacts.getArtifactPath(Artifact.engineDartBinary);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_lowercase_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput0.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput1.txt',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output'))
.parse(args);
final String inputFileContents = fileSystem.file(parsedArgs['input']).readAsStringSync();
fileSystem.file(parsedArgs['output'])
..createSync()
..writeAsStringSync(inputFileContents.toLowerCase());
},
),
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_distance_from_ascii_a_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput1.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput2.txt',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output'))
.parse(args);
final String inputFileContents = fileSystem.file(parsedArgs['input']).readAsStringSync();
final StringBuffer outputContents = StringBuffer();
for (int i = 0; i < inputFileContents.length; i++) {
outputContents.write(inputFileContents.codeUnitAt(i) - 'a'.codeUnits.first);
}
fileSystem.file(parsedArgs['output'])
..createSync()
..writeAsStringSync(outputContents.toString());
},
),
]);
final AssetTransformer transformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: dartBinaryPath,
);
final AssetTransformationFailure? failure = await transformer.transformAsset(
asset: asset,
outputPath: outputPath,
workingDirectory: fileSystem.currentDirectory.path,
transformerEntries: <AssetTransformerEntry>[
const AssetTransformerEntry(
package: 'my_lowercase_transformer',
args: <String>[],
),
const AssetTransformerEntry(
package: 'my_distance_from_ascii_a_transformer',
args: <String>[],
),
],
);
expect(processManager, hasNoRemainingExpectations);
expect(failure, isNull);
expect(fileSystem.file(outputPath).readAsStringSync(), '012');
});
testWithoutContext('prints an error when a transformer in a chain (thats not the first) does not produce an output', () async {
final FileSystem fileSystem = MemoryFileSystem();
final Artifacts artifacts = Artifacts.test();
final File asset = fileSystem.file('asset.txt')
..createSync()
..writeAsStringSync('ABC');
const String outputPath = 'output.txt';
final String dartBinaryPath = artifacts.getArtifactPath(Artifact.engineDartBinary);
final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_lowercase_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput0.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput1.txt',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output'))
.parse(args);
final String inputFileContents = fileSystem.file(parsedArgs['input']).readAsStringSync();
fileSystem.file(parsedArgs['output'])
..createSync()
..writeAsStringSync(inputFileContents.toLowerCase());
},
),
FakeCommand(
command: <String>[
dartBinaryPath,
'run',
'my_distance_from_ascii_a_transformer',
'--input=/.tmp_rand0/asset.txt-transformOutput1.txt',
'--output=/.tmp_rand0/asset.txt-transformOutput2.txt',
],
onRun: (List<String> args) {
// Do nothing.
},
stderr: 'Transformation failed, but I forgot to exit with a non-zero code.'
),
]);
final AssetTransformer transformer = AssetTransformer(
processManager: processManager,
fileSystem: fileSystem,
dartBinaryPath: dartBinaryPath,
);
final AssetTransformationFailure? failure = await transformer.transformAsset(
asset: asset,
outputPath: outputPath,
workingDirectory: fileSystem.currentDirectory.path,
transformerEntries: <AssetTransformerEntry>[
const AssetTransformerEntry(
package: 'my_lowercase_transformer',
args: <String>[],
),
const AssetTransformerEntry(
package: 'my_distance_from_ascii_a_transformer',
args: <String>[],
),
],
);
expect(failure, isNotNull);
expect(failure!.message,
'''
User-defined transformation of asset "asset.txt" failed.
Asset transformer my_distance_from_ascii_a_transformer did not produce an output file.
Input file provided to transformer: "/.tmp_rand0/asset.txt-transformOutput1.txt"
Expected output file at: "/.tmp_rand0/asset.txt-transformOutput2.txt"
Full command: Artifact.engineDartBinary run my_distance_from_ascii_a_transformer --input=/.tmp_rand0/asset.txt-transformOutput1.txt --output=/.tmp_rand0/asset.txt-transformOutput2.txt
stdout:
stderr:
Transformation failed, but I forgot to exit with a non-zero code.'''
);
expect(processManager, hasNoRemainingExpectations);
expect(fileSystem.file(outputPath), isNot(exists));
expect(fileSystem.systemTempDirectory.listSync(), isEmpty);
});
}

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:args/args.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
@@ -9,19 +10,24 @@ import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/build_system/depfile.dart';
import 'package:flutter_tools/src/build_system/targets/assets.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/convert.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import '../../../src/common.dart';
import '../../../src/context.dart';
import '../../../src/fake_process_manager.dart';
void main() {
late Environment environment;
late FileSystem fileSystem;
late BufferLogger logger;
setUp(() {
fileSystem = MemoryFileSystem.test();
@@ -53,6 +59,7 @@ flutter:
- assets/foo/bar.png
- assets/wildcard/
''');
logger = BufferLogger.test();
});
testUsingContext('includes LICENSE file inputs in dependencies', () async {
@@ -157,6 +164,153 @@ flutter:
});
});
testUsingContext('transforms assets declared with transformers', () async {
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: globals.platform,
fileSystem: fileSystem,
userMessages: UserMessages(),
);
final Environment environment = Environment.test(
fileSystem.currentDirectory,
processManager: globals.processManager,
artifacts: Artifacts.test(),
fileSystem: fileSystem,
logger: logger,
platform: globals.platform,
defines: <String, String>{},
);
await fileSystem.file('.packages').create();
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('''
name: example
flutter:
assets:
- path: input.txt
transformers:
- package: my_capitalizer_transformer
args: ["-a", "-b", "--color", "green"]
''');
fileSystem.file('input.txt')
..createSync(recursive: true)
..writeAsStringSync('abc');
await const CopyAssets().build(environment);
expect(logger.errorText, isEmpty);
expect(globals.processManager, hasNoRemainingExpectations);
expect(fileSystem.file('${environment.buildDir.path}/flutter_assets/input.txt'), exists);
}, overrides: <Type, Generator> {
Logger: () => logger,
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: <Pattern>[
Artifacts.test().getArtifactPath(Artifact.engineDartBinary),
'run',
'my_capitalizer_transformer',
RegExp('--input=.*'),
RegExp('--output=.*'),
'-a',
'-b',
'--color',
'green',
],
onRun: (List<String> args) {
final ArgResults parsedArgs = (ArgParser()
..addOption('input')
..addOption('output')
..addOption('color')
..addFlag('aaa', abbr: 'a')
..addFlag('bbb', abbr: 'b'))
.parse(args);
expect(parsedArgs['aaa'], true);
expect(parsedArgs['bbb'], true);
expect(parsedArgs['color'], 'green');
final File input = fileSystem.file(parsedArgs['input'] as String);
expect(input, exists);
final String inputContents = input.readAsStringSync();
expect(inputContents, 'abc');
fileSystem.file(parsedArgs['output'])
..createSync()
..writeAsStringSync(inputContents.toUpperCase());
},
),
],
),
});
testUsingContext('exits tool if an asset transformation fails', () async {
Cache.flutterRoot = Cache.defaultFlutterRoot(
platform: globals.platform,
fileSystem: fileSystem,
userMessages: UserMessages(),
);
final Environment environment = Environment.test(
fileSystem.currentDirectory,
processManager: globals.processManager,
artifacts: Artifacts.test(),
fileSystem: fileSystem,
logger: logger,
platform: globals.platform,
defines: <String, String>{},
);
await fileSystem.file('.packages').create();
fileSystem.file('pubspec.yaml')
..createSync()
..writeAsStringSync('''
name: example
flutter:
assets:
- path: input.txt
transformers:
- package: my_transformer
args: ["-a", "-b", "--color", "green"]
''');
await fileSystem.file('input.txt').create(recursive: true);
await expectToolExitLater(
const CopyAssets().build(environment),
startsWith('User-defined transformation of asset "/input.txt" failed.\n'),
);
expect(globals.processManager, hasNoRemainingExpectations);
}, overrides: <Type, Generator> {
Logger: () => logger,
FileSystem: () => fileSystem,
Platform: () => FakePlatform(),
ProcessManager: () => FakeProcessManager.list(
<FakeCommand>[
FakeCommand(
command: <Pattern>[
Artifacts.test().getArtifactPath(Artifact.engineDartBinary),
'run',
'my_transformer',
RegExp('--input=.*'),
RegExp('--output=.*'),
'-a',
'-b',
'--color',
'green',
],
exitCode: 1,
),
],
),
});
testUsingContext('Throws exception if pubspec contains missing files', () async {
fileSystem.file('pubspec.yaml')
..createSync()
@@ -182,7 +336,7 @@ flutter:
null,
targetPlatform: TargetPlatform.android,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
logger: logger,
), isNull);
});
@@ -193,7 +347,7 @@ flutter:
'does_not_exist.sksl',
targetPlatform: TargetPlatform.android,
fileSystem: MemoryFileSystem.test(),
logger: BufferLogger.test(),
logger: logger,
), throwsException);
});

View File

@@ -20,6 +20,7 @@ import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/tools/shader_compiler.dart';
import 'package:flutter_tools/src/compile.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/flutter_manifest.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:package_config/package_config.dart';
import 'package:test/fake.dart';
@@ -623,10 +624,12 @@ void main() {
..entries['foo.frag'] = AssetBundleEntry(
DevFSByteContent(<int>[1, 2, 3, 4]),
kind: AssetKind.shader,
transformers: const <AssetTransformerEntry>[],
)
..entries['not.frag'] = AssetBundleEntry(
DevFSByteContent(<int>[1, 2, 3, 4]),
kind: AssetKind.regular,
transformers: const <AssetTransformerEntry>[],
);
final UpdateFSReport report = await devFS.update(
@@ -680,6 +683,7 @@ void main() {
..entries['FontManifest.json'] = AssetBundleEntry(
DevFSByteContent(<int>[1, 2, 3, 4]),
kind: AssetKind.regular,
transformers: const <AssetTransformerEntry>[],
);
final UpdateFSReport report = await devFS.update(