Short-circuit crawling all targets in et {build|test|query} (flutter/engine#52832)

Closes https://github.com/flutter/flutter/issues/147666.

This is a large change, I'd be happy to either review synchronously or
change commands one at a time, but I think this is overall the right
approach. I also didn't see any reason to reuse the `BuildRunner` code
for these commands, the flow is basically:

```mermaid
graph LR
    A[et targetsOrPatterns] --> B[gn desc --format=json]
    B --> C[existing code that runs ninja/workers]
```

Quick summary of changes:
- Introduced a [`Label` and `TargetPattern`][1] type to avoid awkward
string parsing/manipulation all over
- Replaced `gn_utils` (i.e. `targetsFromCommandLine` and friends) with
[an invocation of `gn desc`][2]
- Some tests were brittle in terms of expected output, I mostly left
them alone and wrote TODOs where applicable

Here is the fun part, results (and some manual integration tests):
```sh
# build, previously was 10-15s, is now ~3s
flutter % time et build -c host_debug_unopt_arm64 //flutter/impeller:impeller_unittests
[2024-05-14T19:05:55.163][macos/host_debug_unopt_arm64: GN]: OK
[2024-05-14T19:05:56.119][macos/host_debug_unopt_arm64: RBE startup]: Proxy started successfully.
[macos/host_debug_unopt_arm64: ninja] 0.0% (0/1) Regenerating ninja files[2024-05-14T19:05:57.309][macos/host_debug_unopt_arm64: ninja]: OK
[2024-05-14T19:05:57.573][macos/host_debug_unopt_arm64: RBE shutdown]: Actions completed: 0
$ENGINE/flutter/bin/et build -c host_debug_unopt_arm64   3.20s user 0.87s system 107% cpu 3.776 total

# test, also benefits from speedup, but I didn't time it
flutter % et test -c host_debug_unopt_arm64 //flutter/fml:fml_unittests
[2024-05-14T19:07:01.843][macos/host_debug_unopt_arm64: GN]: OK
[2024-05-14T19:07:02.707][macos/host_debug_unopt_arm64: RBE startup]: Proxy started successfully.
[2024-05-14T19:07:07.400][macos/host_debug_unopt_arm64: ninja]: 100.0% (3/3) LINK ./fml_unittests
[2024-05-14T19:07:07.404][macos/host_debug_unopt_arm64: ninja]: OK
[2024-05-14T19:07:07.748][macos/host_debug_unopt_arm64: RBE shutdown]: Actions completed: 1 (1 racing local)
OKAY:         7s.95ms //flutter/fml:fml_unittests

# query, also benefits from speedup
flutter % time et query targets -c host_debug_unopt_arm64
//flutter/display_list:display_list_benchmarks
//flutter/display_list:display_list_builder_benchmarks
# ... many targets omitted ...
$ENGINE/flutter/bin/et query targets -c host_debug_unopt_arm64  1.27s user 0.18s system 147% cpu 0.978 total
```

In other words, ~5x improvement on `et build` and `et query` is _much_
faster as well.

[1]:
https://github.com/flutter/engine/compare/main...matanlurey:engine:gn-label?expand=1#diff-ac008475ce9e209f4ecf6594b0cd48d12d86a1ffa0aa7d555375ff43b983eb2b
[2]:
https://github.com/flutter/engine/compare/main...matanlurey:engine:gn-label?expand=1#diff-ad116b8504dd0a500bf758a327c7052e5733a2b465d3295e35b74458d483276f
This commit is contained in:
Matan Lurey
2024-05-15 12:57:02 -07:00
committed by GitHub
parent 33592ed533
commit cb19eac08e
16 changed files with 694 additions and 511 deletions

View File

@@ -5,6 +5,7 @@
import 'package:engine_build_configs/engine_build_configs.dart';
import 'environment.dart';
import 'label.dart';
import 'logger.dart';
/// A function that returns true or false when given a [BuilderConfig] and its
@@ -121,7 +122,7 @@ Future<int> runBuild(
Build build, {
required bool enableRbe,
List<String> extraGnArgs = const <String>[],
List<String> targets = const <String>[],
List<Label> targets = const <Label>[],
}) async {
final List<String> gnArgs = <String>[
if (!enableRbe) '--no-rbe',
@@ -138,7 +139,7 @@ Future<int> runBuild(
extraGnArgs: gnArgs,
runTests: false,
extraNinjaArgs: <String>[
...targets,
...targets.map((Label label) => label.toNinjaLabel()),
// If the environment is verbose, pass the verbose flag to ninja.
if (environment.verbose) '--verbose',
],

View File

@@ -5,7 +5,8 @@
import 'package:engine_build_configs/engine_build_configs.dart';
import '../build_utils.dart';
import '../gn_utils.dart';
import '../gn.dart';
import '../label.dart';
import 'command.dart';
import 'flags.dart';
@@ -48,8 +49,9 @@ final class BuildCommand extends CommandBase {
@override
String get description => '''
Builds the engine
et build //flutter/fml/... # Build all targets in `//flutter/fml/`
et build //flutter/fml:fml_benchmarks # Build a specific target in `//flutter/fml/`
et build //flutter/fml/... # Build all targets in `//flutter/fml` and its subdirectories.
et build //flutter/fml:all # Build all targets in `//flutter/fml`.
et build //flutter/fml:fml_benchmarks # Build a specific target in `//flutter/fml`.
''';
@override
@@ -71,32 +73,27 @@ et build //flutter/fml:fml_benchmarks # Build a specific target in `//flutter/f
final List<String> extraGnArgs = <String>[
if (!useRbe) '--no-rbe',
if (useLto) '--lto',
if (!useLto) '--no-lto',
if (useLto) '--lto' else '--no-lto',
];
final List<BuildTarget>? selectedTargets = await targetsFromCommandLine(
environment,
build,
argResults!.rest,
enableRbe: useRbe,
);
if (selectedTargets == null) {
// The user typed something wrong and targetsFromCommandLine has already
// logged the error message.
return 1;
// Builds only accept labels as arguments, so convert patterns to labels.
// TODO(matanlurey): Can be optimized in cases where wildcards are not used.
final Gn gn = Gn.fromEnvironment(environment);
final Set<Label> allTargets = <Label>{};
for (final String pattern in argResults!.rest) {
final TargetPattern target = TargetPattern.parse(pattern);
final List<BuildTarget> targets = await gn.desc(
'out/${build.ninja.config}',
target,
);
allTargets.addAll(targets.map((BuildTarget target) => target.label));
}
// Chop off the '//' prefix.
final List<String> ninjaTargets = selectedTargets.map<String>(
(BuildTarget target) => target.label.substring('//'.length),
).toList();
return runBuild(
environment,
build,
extraGnArgs: extraGnArgs,
targets: ninjaTargets,
targets: allTargets.toList(),
enableRbe: useRbe,
);
}

View File

@@ -95,8 +95,8 @@ final class ToolCommandRunner extends CommandRunner<int> {
Future<int> run(Iterable<String> args) async {
try {
return await runCommand(parse(args)) ?? 0;
} on FormatException catch (e) {
environment.logger.error(e);
} on FormatException catch (e, s) {
environment.logger.error('$e\n$s');
return 1;
} on UsageException catch (e) {
environment.logger.error(e);

View File

@@ -84,7 +84,6 @@ final class LintCommand extends CommandBase {
if (environment.platform.isWindows) {
environment.logger
.fatal('lint command is not supported on Windows (for now).');
return 1;
}
final WorkerPool wp =
WorkerPool(environment, ProcessTaskProgressReporter(environment));

View File

@@ -5,7 +5,8 @@
import 'package:engine_build_configs/engine_build_configs.dart';
import '../build_utils.dart';
import '../gn_utils.dart';
import '../gn.dart';
import '../label.dart';
import 'command.dart';
import 'flags.dart';
@@ -194,27 +195,33 @@ et query targets //flutter/fml/... # List all targets under `//flutter/fml`
return 1;
}
final List<BuildTarget>? selectedTargets = await targetsFromCommandLine(
environment,
build,
argResults!.rest,
defaultToAll: true,
enableRbe: useRbe,
);
if (selectedTargets == null) {
// The user typed something wrong and targetsFromCommandLine has already
// logged the error message.
return 1;
}
if (selectedTargets.isEmpty) {
environment.logger.fatal(
'targetsFromCommandLine unexpectedly returned an empty list',
);
// Builds only accept labels as arguments, so convert patterns to labels.
// TODO(matanlurey): Can be optimized in cases where wildcards are not used.
final Gn gn = Gn.fromEnvironment(environment);
// TODO(matanlurey): Discuss if we want to just require '//...'.
// For now this retains the existing behavior.
List<String> patterns = argResults!.rest;
if (patterns.isEmpty) {
patterns = <String>['//...'];
}
for (final BuildTarget target in selectedTargets) {
if (testOnly &&
(!target.testOnly || target.type != BuildTargetType.executable)) {
final Set<BuildTarget> allTargets = <BuildTarget>{};
for (final String pattern in patterns) {
final TargetPattern target = TargetPattern.parse(pattern);
final List<BuildTarget> targets = await gn.desc(
'out/${build.ninja.config}',
target,
);
allTargets.addAll(targets);
}
if (allTargets.isEmpty) {
environment.logger.fatal('Query unexpectedly returned an empty list');
}
for (final BuildTarget target in allTargets) {
if (testOnly && (!target.testOnly || target is! ExecutableBuildTarget)) {
continue;
}
environment.logger.status(target.label);

View File

@@ -5,7 +5,8 @@
import 'package:engine_build_configs/engine_build_configs.dart';
import '../build_utils.dart';
import '../gn_utils.dart';
import '../gn.dart';
import '../label.dart';
import '../proc_utils.dart';
import '../worker_pool.dart';
import 'command.dart';
@@ -46,8 +47,9 @@ final class TestCommand extends CommandBase {
@override
String get description => '''
Runs a test target
et test //flutter/fml/... # Run all test targets in `//flutter/fml/`
et test //flutter/fml:fml_benchmarks # Run a single test target in `//flutter/fml/`
et test //flutter/fml/... # Run all test targets in `//flutter/fml` and its subdirectories.
et test //flutter/fml:all # Run all test targets in `//flutter/fml`.
et test //flutter/fml:fml_benchmarks # Run a single test target in `//flutter/fml`.
''';
@override
@@ -66,63 +68,53 @@ et test //flutter/fml:fml_benchmarks # Run a single test target in `//flutter/f
return 1;
}
final List<BuildTarget>? selectedTargets = await targetsFromCommandLine(
environment,
build,
argResults!.rest,
defaultToAll: true,
enableRbe: useRbe,
);
if (selectedTargets == null) {
// The user typed something wrong and targetsFromCommandLine has already
// logged the error message.
return 1;
}
if (selectedTargets.isEmpty) {
environment.logger.fatal(
'targetsFromCommandLine unexpectedly returned an empty list',
// Builds only accept labels as arguments, so convert patterns to labels.
final Gn gn = Gn.fromEnvironment(environment);
// Figure out what targets the user wants to build.
final Set<BuildTarget> buildTargets = <BuildTarget>{};
for (final String pattern in argResults!.rest) {
final TargetPattern target = TargetPattern.parse(pattern);
final List<BuildTarget> found = await gn.desc(
'out/${build.ninja.config}',
target,
);
buildTargets.addAll(found);
}
final List<BuildTarget> testTargets = <BuildTarget>[];
for (final BuildTarget target in selectedTargets) {
if (_isTestExecutable(target)) {
testTargets.add(target);
}
if (target.executable == null) {
environment.logger.fatal(
'$target is an executable but is missing the executable path');
}
// Make sure there is at least one test target.
final List<ExecutableBuildTarget> testTargets = buildTargets
.whereType<ExecutableBuildTarget>()
.where((ExecutableBuildTarget t) => t.testOnly).toList();
if (testTargets.isEmpty) {
environment.logger.error('No test targets found');
return 1;
}
// Chop off the '//' prefix.
final List<String> buildTargets = testTargets
.map<String>(
(BuildTarget target) => target.label.substring('//'.length))
.toList();
// TODO(johnmccutchan): runBuild manipulates buildTargets and adds some
// targets listed in Build. Fix this.
final int buildExitCode = await runBuild(
environment,
build,
targets: buildTargets,
targets: testTargets.map((BuildTarget target) => target.label).toList(),
enableRbe: useRbe,
);
if (buildExitCode != 0) {
return buildExitCode;
}
final WorkerPool workerPool =
WorkerPool(environment, ProcessTaskProgressReporter(environment));
final WorkerPool workerPool = WorkerPool(
environment,
ProcessTaskProgressReporter(environment),
);
final Set<ProcessTask> tasks = <ProcessTask>{};
for (final BuildTarget target in testTargets) {
final List<String> commandLine = <String>[target.executable!.path];
for (final ExecutableBuildTarget target in testTargets) {
final List<String> commandLine = <String>[target.executable];
tasks.add(ProcessTask(
target.label, environment, environment.engine.srcDir, commandLine));
target.label.toString(),
environment,
environment.engine.srcDir,
commandLine,
));
}
return await workerPool.run(tasks) ? 0 : 1;
}
/// Returns true if `target` is a testonly executable.
static bool _isTestExecutable(BuildTarget target) {
return target.testOnly && target.type == BuildTargetType.executable;
}
}

View File

@@ -0,0 +1,187 @@
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'package:process_runner/process_runner.dart';
import 'environment.dart';
import 'label.dart';
import 'typed_json.dart';
/// An interface to the [GN](https://gn.googlesource.com/gn) build system.
///
/// See also: <https://gn.googlesource.com/gn/+/main/docs/reference.md>.
interface class Gn {
/// Create a new GN interface using the given [environment].
///
/// A GN binary must exist in `{engine.srcDir}/flutter/third_party/gn/gn`[^1].
///
/// [^1]: On Windows, the binary is named `gn.exe`.
const Gn.fromEnvironment(this._environment);
final Environment _environment;
String get _gnPath => p.join(
_environment.engine.srcDir.path,
'flutter',
'third_party',
'gn',
_environment.platform.isWindows ? 'gn.exe' : 'gn',
);
/// Returns a list of build targets that match the given [pattern].
///
/// This is equivalent to running:
/// ```sh
/// gn desc {outDir} {labelOrPattern}
/// ```
///
/// The [outDir] is the output directory of the build, e.g. `out/Release`.
///
/// See also: <https://gn.googlesource.com/gn/+/main/docs/reference.md#cmd_desc>.
Future<List<BuildTarget>> desc(
String outDir,
TargetPattern pattern,
) async {
final List<String> command = <String>[
_gnPath,
'desc',
'--format=json',
outDir,
pattern.toGnPattern(),
];
final ProcessRunnerResult process = await _environment.processRunner.runProcess(
command,
workingDirectory: _environment.engine.srcDir,
failOk: true,
);
if (process.exitCode != 0) {
_environment.logger.fatal(
'Failed to run `${command.join(' ')}` (exit code ${process.exitCode})'
'\n\n'
'STDOUT:\n${process.stdout}\n'
'STDERR:\n${process.stderr}\n',
);
}
final JsonObject result;
try {
result = JsonObject.parse(process.stdout);
} on FormatException catch (e) {
_environment.logger.fatal(
'Failed to parse JSON output from `gn desc`:\n$e',
);
}
return result.asMap().entries.map((MapEntry<String, Object?> entry) {
final String label = entry.key;
final Object? properties = entry.value;
if (properties is! Map<String, Object?>) {
return null;
}
final BuildTarget? target = BuildTarget._fromJson(
label,
JsonObject(properties),
);
if (target == null) {
return null;
}
return target;
}).whereType<BuildTarget>().toList();
}
}
/// Information about a build target.
@immutable
sealed class BuildTarget {
const BuildTarget({
required this.label,
required this.testOnly,
});
/// Returns a build target from JSON originating from `gn desc --format=json`.
///
/// If the JSON is not a supported build target, returns `null`.
static BuildTarget? _fromJson(String label, JsonObject json) {
final (
String type,
bool testOnly,
) = json.map((JsonObject json) => (
json.string('type'),
json.boolean('testonly'),
));
return switch (type) {
'executable' => ExecutableBuildTarget(
label: Label.parseGn(label),
testOnly: testOnly,
// Remove the leading // from the path.
executable: json.stringList('outputs').first.substring(2),
),
'shared_library' || 'static_library' => LibraryBuildTarget(
label: Label.parseGn(label),
testOnly: testOnly,
),
_ => null,
};
}
/// Build target label, e.g. `//flutter/fml:fml_unittests`.
final Label label;
/// Whether a target is only used for testing.
final bool testOnly;
@mustBeOverridden
@override
bool operator ==(Object other);
@mustBeOverridden
@override
int get hashCode;
}
/// A build target that produces a [shared library][] or [static library][].
///
/// [shared library]: https://gn.googlesource.com/gn/+/main/docs/reference.md#func_shared_library
/// [static library]: https://gn.googlesource.com/gn/+/main/docs/reference.md#func_static_library
final class LibraryBuildTarget extends BuildTarget {
/// Construct a library build target.
const LibraryBuildTarget({
required super.label,
required super.testOnly,
});
@override
bool operator ==(Object other) {
return other is LibraryBuildTarget &&
label == other.label &&
testOnly == other.testOnly;
}
@override
int get hashCode => Object.hash(label, testOnly);
}
/// A build target that produces an [executable][] program.
///
/// [executable]: https://gn.googlesource.com/gn/+/main/docs/reference.md#func_executable
final class ExecutableBuildTarget extends BuildTarget {
/// Construct an executable build target.
const ExecutableBuildTarget({
required super.label,
required super.testOnly,
required this.executable,
});
/// The path to the executable program.
final String executable;
@override
bool operator ==(Object other) {
return other is ExecutableBuildTarget &&
label == other.label &&
testOnly == other.testOnly &&
executable == other.executable;
}
@override
int get hashCode => Object.hash(label, testOnly, executable);
}

View File

@@ -1,273 +0,0 @@
// Copyright 2013 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 'dart:convert';
import 'dart:io';
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:path/path.dart' as p;
import 'package:process_runner/process_runner.dart';
import 'build_utils.dart';
import 'environment.dart';
import 'proc_utils.dart';
import 'typed_json.dart';
/// Canonicalized build targets start with this prefix.
const String buildTargetPrefix = '//';
/// A suffix to build targets that recursively selects all child build targets.
const String _buildTargetGlobSuffix = '/...';
/// The type of a BuildTarget
enum BuildTargetType {
/// Produces an executable program.
executable,
/// Produces a shared library.
sharedLibrary,
/// Produces a static library.
staticLibrary,
}
BuildTargetType? _buildTargetTypeFromString(String type) {
switch (type) {
case 'executable':
return BuildTargetType.executable;
case 'shared_library':
return BuildTargetType.sharedLibrary;
case 'static_library':
return BuildTargetType.staticLibrary;
default:
// We ignore a number of types here.
return null;
}
}
// TODO(johnmccutchan): What should we do about source_sets and other
// output-less targets? Also, what about action targets which are kind of
// "internal" build steps? For now we are ignoring them.
/// Information about a build target.
final class BuildTarget {
//// Construct a build target.
BuildTarget(this.type, this.label, {this.executable, this.testOnly = false});
/// The type of build target.
final BuildTargetType type;
/// The build target label. `//flutter/fml:fml_unittests`.
final String label;
/// The executable file produced after the build target is built.
final File? executable;
/// Is this a target that is only used by tests?
final bool testOnly;
@override
String toString() {
return 'target=$label type=$type testOnly=$testOnly executable=${executable ?? "N/A"}';
}
}
/// Returns all targets for a given build directory.
Future<Map<String, BuildTarget>> findTargets(
Environment environment, Directory buildDir) async {
final Map<String, BuildTarget> r = <String, BuildTarget>{};
final Map<String, Object?> jsonResult =
await _runGnDesc(buildDir.path, '*', environment);
for (final MapEntry<String, Object?> targetEntry in jsonResult.entries) {
final String label = targetEntry.key;
if (targetEntry.value == null) {
environment.logger
.fatal('gn desc output is malformed $label has no value.');
}
final JsonObject properties = JsonObject(targetEntry.value! as Map<String, Object?>);
final String? typeString = properties.stringOrNull('type');
if (typeString == null) {
environment.logger.fatal('gn desc is missing target type: $properties');
}
final BuildTargetType? type = _buildTargetTypeFromString(typeString!);
if (type == null) {
// Target is a type that we don't support.
continue;
}
final bool testOnly = properties.boolean('testonly');
final List<String> outputs =
await _runGnOutputs(buildDir.path, label, environment);
File? executable;
if (type == BuildTargetType.executable) {
if (outputs.isEmpty) {
environment.logger.fatal('gn executable target $label has no outputs.');
}
executable = File(p.join(buildDir.path, outputs.first));
}
final BuildTarget target =
BuildTarget(type, label, testOnly: testOnly, executable: executable);
r[label] = target;
}
return r;
}
/// Returns the JSON output of running `gn desc buildDir label`.
Future<Map<String, Object?>> _runGnDesc(
String buildDir, String label, Environment environment) async {
final List<String> commandline = <String>[
gnBinPath(environment),
'desc',
buildDir,
label,
'--format=json',
];
final ProcessRunnerResult result = await environment.processRunner.runProcess(
commandline,
workingDirectory: environment.engine.srcDir,
failOk: true);
// Handle any process failures.
fatalIfFailed(environment, commandline, result);
late final Map<String, Object?> jsonResult;
try {
jsonResult = jsonDecode(result.stdout) as Map<String, Object?>;
} catch (e) {
environment.logger.fatal(
'gn desc output could not be parsed:\nE=$e\nIN=${result.stdout}\n');
}
return jsonResult;
}
/// Returns the output paths returned by `gn outputs buildDir label`.
Future<List<String>> _runGnOutputs(
String buildDir, String label, Environment environment) async {
final List<String> commandline = <String>[
gnBinPath(environment),
'outputs',
buildDir,
label,
];
final ProcessRunnerResult result = await environment.processRunner.runProcess(
commandline,
workingDirectory: environment.engine.srcDir,
failOk: true);
// Handle any process failures.
fatalIfFailed(environment, commandline, result);
return result.stdout.split('\n');
}
/// Process selectors and filter allTargets for matches.
///
/// We support:
/// 1) Exact label matches (the '//' prefix will be stripped off).
/// 2) '/...' suffix which selects all targets that match the prefix.
///
/// NOTE: if selectors is empty all targets will be selected.
Set<BuildTarget> selectTargets(
List<String> selectors, Map<String, BuildTarget> allTargets) {
final Set<BuildTarget> selected = <BuildTarget>{};
if (selectors.isEmpty) {
// Default to all if no selectors are specified.
// TODO(johnmccutchan): Reconsider this default or at least lift
// this logic up to the caller.
allTargets.values.forEach(selected.add);
return selected;
}
for (String selector in selectors) {
if (!selector.startsWith(buildTargetPrefix)) {
// Insert the prefix when necessary.
selector = '$buildTargetPrefix$selector';
}
final bool recursiveMatch = selector.endsWith(_buildTargetGlobSuffix);
if (recursiveMatch) {
// Remove the /... suffix.
selector = selector.substring(
0, selector.length - _buildTargetGlobSuffix.length);
// TODO(johnmccutchan): Accelerate this by using a trie.
for (final BuildTarget target in allTargets.values) {
if (target.label.startsWith(selector)) {
selected.add(target);
}
}
} else {
for (final BuildTarget target in allTargets.values) {
if (target.label == selector) {
selected.add(target);
}
}
}
}
return selected;
}
/// Given a list of target specifications from the command line, return a list
/// of [BuildTarget]s from the [Build] that match those specifications.
///
/// If `commandLineTargets` is empty, by default this will return the empty
/// list, which indicates that the caller should delegate the selection of
/// build targets to whatever is specified by the [Build] object. However,
/// if `defaultToAll` is `true`, then this function will return the list of
/// all build targets.
Future<List<BuildTarget>?> targetsFromCommandLine(
Environment environment,
Build build,
List<String> commandLineTargets, {
bool defaultToAll = false,
required bool enableRbe,
}) async {
// If there are no targets specified on the command line, then delegate to
// the default targets specified in the Build object unless directed
// otherwise by the defaultToAll argument.
if (commandLineTargets.isEmpty && !defaultToAll) {
return <BuildTarget>[];
}
final Directory buildDir = Directory(p.join(
environment.engine.outDir.path,
build.ninja.config,
));
// If the expected build output directory doesn't exist yet, eagerly run
// the build's GN step to try to produce it.
if (!buildDir.existsSync()) {
environment.logger.status(
'Build output directory at ${buildDir.path} not found. Running GN.',
);
final int gnResult = await runGn(environment, build, enableRbe: enableRbe);
if (gnResult != 0 || !buildDir.existsSync()) {
environment.logger.error(
'The specified build did not produce the expected build '
'output directory.',
);
return null;
}
}
// Find all targets buildable in the configuration.
final Map<String, BuildTarget> allTargets = await findTargets(
environment,
buildDir,
);
// Use the targets specified on the command line to filter the list of
// all targets.
final Set<BuildTarget> selectedTargets = selectTargets(
commandLineTargets,
allTargets,
);
// Report an error if applying the filter yields no results.
if (selectedTargets.isEmpty) {
environment.logger.error(
'No build targets matched ${commandLineTargets.join(',')}\n'
'Run `et query targets` to see list of targets.',
);
return null;
}
return selectedTargets.toList();
}

View File

@@ -0,0 +1,250 @@
// Copyright 2013 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:meta/meta.dart';
/// An identifier of a target that loosely follows [GN][] and [Bazel][] format.
///
/// [gn]: https://gn.googlesource.com/gn/+/master/docs/reference.md#labels
/// [bazel]: https://bazel.build/concepts/labels
///
/// A label in `engine_tool` are two string components separated by a colon in
/// the format `//path/to/package-name:target-name`, with constraints on the
/// characters that can be used in each component (see [package] and [target]).
///
/// Unlike counterparts in Bazel and GN:
/// - The package name is always a source-absolute path (i.e. starts with `//`).
/// - Valid identifier characters are `a-zA-Z0-9_-`, not starting with a digit.
/// - The target name is never empty, even when it is a default target.
@immutable
final class Label {
/// Creates a new label with the given package and target name.
///
/// If [target] is omitted, the final component of [package] is used as the
/// target name (e.g. `//name` becomes `//name:name`).
///
/// Throws a [FormatException] if the package or target name is invalid.
factory Label(String package, [String? target]) {
final FormatException? packageError = _checkPackage(package);
if (packageError != null) {
throw packageError;
}
target ??= package.substring(package.lastIndexOf('/') + 1);
final FormatException? targetError = _checkTarget(target);
if (targetError != null) {
throw targetError;
}
return Label._(package, target);
}
const Label._(this.package, this.target);
/// Parses a label from a string in the format `//package-name:target-name`.
///
/// Throws a [FormatException] if the label is invalid.
static Label parse(String label) {
final int colon = label.indexOf(':');
if (colon == -1) {
return Label(label);
}
return Label(label.substring(0, colon), label.substring(colon + 1));
}
/// Parses a label from a string in the format `//package-name:target-name`.
///
/// If a toolchain is present, it is removed.
///
/// Throws a [FormatException] if the label is invalid.
static Label parseGn(String label) {
// Remove (//build/toolchain/...) at the end of the label.
if (label.endsWith(')')) {
final int start = label.lastIndexOf('(', label.length - 2);
if (start != -1) {
label = label.substring(0, start);
}
}
return Label.parse(label);
}
/// A source-absolute package name, starting with `//`.
///
/// The package name must be a valid identifier, i.e. it must be a sequence of
/// identifier components separated by slashes and cannot end with a slash.
final String package;
/// A target name within the package.
///
/// The target name must be a valid identifier.
final String target;
@override
bool operator ==(Object other) {
return other is Label && package == other.package && target == other.target;
}
@override
int get hashCode => Object.hash(package, target);
/// Returns a string representation of the label (i.e. used by [parse]).
///
/// Use [toNinjaLabel] to remove the leading `//` from the package name.
@override
String toString() => '$package:$target';
/// Returns a Ninja-compatible string representation of the label.
///
/// `//package-name:target-name` becomes `package-name:target-name`.
String toNinjaLabel() => '${package.substring(2)}:$target';
static FormatException? _checkPackage(String package) {
// Must start with a double slash.
if (!package.startsWith('//')) {
return FormatException(
'Package name must start with "//".',
package,
);
}
// Cannot end with a slash.
if (package.endsWith('/')) {
return FormatException(
'Package name must not end with a slash.',
package,
);
}
// Check each component of the package name for valid identifier characters.
// We use a standard loop to give a better error message.
int i = 2;
while (true) {
final int j = package.indexOf('/', i);
final String component =
j == -1 ? package.substring(i) : package.substring(i, j);
if (!_identifier.hasMatch(component)) {
return FormatException(
'Package name component must be a valid identifier.',
package,
i,
);
}
if (j == -1) {
return null;
}
i = j + 1;
}
}
static FormatException? _checkTarget(String target) {
if (!_identifier.hasMatch(target)) {
return FormatException(
'Target name must be a valid identifier.',
target,
);
}
return null;
}
static final RegExp _identifier = RegExp(r'^[a-zA-Z_][a-zA-Z0-9_-]*$');
}
/// A generic target pattern that can be used to match multiple targets.
///
/// Similar to [Label], but supports wildcards in the package and target name:
/// - `//path/to/package/...` all targets in the package and its subpackages.
/// - `//path/to/package:all` all targets in the package.
///
/// Inspired by <https://bazel.build/run/build#specifying-build-targets>.
@immutable
final class TargetPattern {
/// Creates a new pattern with the given package and target name.
///
/// If [target] is omitted, the pattern matches all targets in the package.
factory TargetPattern(String package, [String? target]) {
// We are so close to a Label that we can reuse the same checks.
// The only difference is that the package name can end with `...`.
bool packageEndsWithWildcard = false;
if (package.endsWith('/...')) {
packageEndsWithWildcard = true;
package = package.substring(0, package.length - 4);
}
// Edgecase: //... is a valid pattern that matches all targets.
if (packageEndsWithWildcard && package == '/') {
return const TargetPattern._('//...', null);
}
// Throws a FormatException if the package or target name is invalid.
final Label label = Label(package, target);
return TargetPattern._(
packageEndsWithWildcard ? '${label.package}...' : label.package,
packageEndsWithWildcard ? null : label.target,
);
}
const TargetPattern._(this.package, this.target);
/// Parses a pattern from a string in the format `//package-name:target-name`.
///
/// Throws a [FormatException] if the pattern is invalid.
static TargetPattern parse(String pattern) {
final int colon = pattern.indexOf(':');
if (colon == -1) {
return TargetPattern(pattern);
}
return TargetPattern(
pattern.substring(0, colon),
pattern.substring(colon + 1),
);
}
/// A source-absolute package name optionally ending with `...`.
final String package;
/// A target name within the package, or `all` to match all targets.
///
/// If [package] ends with `...`, [target] must be `null`.
final String? target;
@override
bool operator ==(Object other) {
return other is TargetPattern &&
package == other.package &&
target == other.target;
}
@override
int get hashCode => Object.hash(package, target);
/// Returns a string representation of the target pattern.
///
/// The string representation is compatible with [parse].
@override
String toString() => target == null ? package : '$package:$target';
/// Returns a string representation of the target pattern in [GN format][gn].
///
/// [gn]: https://gn.googlesource.com/gn/+/master/docs/reference.md#labels
///
/// Specifically:
/// - `//package/to/package/...` is converted to `path/to/package/*`.
/// - `//package/to/package:all` is converted to `path/to/package:*`.
String toGnPattern() {
// Remove the leading `//` and replace `...` and `all`.
final String package = this.package.substring(2);
if (target == null) {
assert(package.endsWith('...'));
// Edgecase: //... is a valid pattern that matches all targets.
if (package == '...') {
return '/*';
}
return package.replaceRange(package.length - 3, package.length, '/*');
}
return '$package:${target == 'all' ? '*' : target}';
}
}

View File

@@ -115,7 +115,7 @@ class Logger {
/// Record a log message level [Logger.error] and throw a FatalError.
/// This should only be called when the program has entered an impossible
/// to recover from state or when something isn't implemented yet.
void fatal(
Never fatal(
Object? message, {
int indent = 0,
bool newline = true,

View File

@@ -287,6 +287,13 @@ extension type const JsonObject(Map<String, Object?> _object) {
}
}
/// Returns the underlying JSON object as a [Map].
///
/// This method is useful for passing the JSON object to APIs that expect a
/// [Map] type, but it is generally recommended to use the provided methods
/// for type-safe access to the JSON values.
Map<String, Object?> asMap() => _object;
/// Returns a "pretty" JSON representation of this object.
String toPrettyString() {
return const JsonEncoder.withIndent(' ').convert(_object);

View File

@@ -383,7 +383,11 @@ void main() {
command[0].contains('ninja') &&
command[1].contains('-C') &&
command[2].endsWith('/host_debug') &&
command[3] == 'flutter/fml:fml_arc_unittests';
// TODO(matanlurey): Tighten this up to be more specific.
// The reason we need a broad check is because the test fixture
// always returns multiple targets for gn desc, even though that is
// not the actual behavior.
command.sublist(3).contains('flutter/fml:fml_arc_unittests');
}));
} finally {
testEnv.cleanup();

View File

@@ -1,129 +0,0 @@
// Copyright 2013 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 'dart:convert' as convert;
import 'dart:io' as io;
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:engine_tool/src/build_utils.dart';
import 'package:engine_tool/src/environment.dart';
import 'package:engine_tool/src/gn_utils.dart';
import 'package:litetest/litetest.dart';
import 'package:platform/platform.dart';
import 'fixtures.dart' as fixtures;
import 'utils.dart';
void main() {
final Engine engine;
try {
engine = Engine.findWithin();
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
final BuilderConfig linuxTestConfig = BuilderConfig.fromJson(
path: 'ci/builders/linux_test_config.json',
map: convert.jsonDecode(fixtures.testConfig('Linux', Platform.linux))
as Map<String, Object?>,
);
final Map<String, BuilderConfig> configs = <String, BuilderConfig>{
'linux_test_config': linuxTestConfig,
};
final List<CannedProcess> cannedProcesses = <CannedProcess>[
CannedProcess((List<String> command) => command.contains('desc'),
stdout: fixtures.gnDescOutput()),
CannedProcess((List<String> command) => command.contains('outputs'),
stdout: 'display_list_unittests'),
];
test('find test targets', () async {
final TestEnvironment testEnvironment =
TestEnvironment(engine, cannedProcesses: cannedProcesses);
final Environment env = testEnvironment.environment;
final Map<String, BuildTarget> testTargets =
await findTargets(env, engine.outDir);
expect(testTargets.length, equals(3));
expect(testTargets['//flutter/display_list:display_list_unittests'],
notEquals(null));
expect(
testTargets['//flutter/display_list:display_list_unittests']!
.executable!
.path,
endsWith('display_list_unittests'));
});
test('process queue failure', () async {
final TestEnvironment testEnvironment =
TestEnvironment(engine, cannedProcesses: cannedProcesses);
final Environment env = testEnvironment.environment;
final Map<String, BuildTarget> testTargets =
await findTargets(env, engine.outDir);
expect(selectTargets(<String>['//...'], testTargets).length, equals(3));
expect(
selectTargets(<String>['//flutter/display_list'], testTargets).length,
equals(0));
expect(
selectTargets(<String>['//flutter/display_list/...'], testTargets)
.length,
equals(1));
expect(
selectTargets(<String>['//flutter/display_list:display_list_unittests'],
testTargets)
.length,
equals(1));
});
test('targetsFromCommandLine respects defaultToAll when false', () async {
final TestEnvironment testEnv = TestEnvironment.withTestEngine(
cannedProcesses: cannedProcesses,
);
try {
final Environment env = testEnv.environment;
final List<Build> builds = runnableBuilds(env, configs, true);
final Build? build = builds.where(
(Build build) => build.name == 'linux/host_debug',
).firstOrNull;
final List<BuildTarget>? selectedTargets = await targetsFromCommandLine(
env,
build!,
<String>[],
enableRbe: false,
);
expect(selectedTargets, isNotNull);
expect(selectedTargets, isEmpty);
} finally {
testEnv.cleanup();
}
});
test('targetsFromCommandLine respects defaultToAll when true', () async {
final TestEnvironment testEnv = TestEnvironment.withTestEngine(
cannedProcesses: cannedProcesses,
);
try {
final Environment env = testEnv.environment;
final List<Build> builds = runnableBuilds(env, configs, true);
final Build? build = builds.where(
(Build build) => build.name == 'linux/host_debug',
).firstOrNull;
final List<BuildTarget>? selectedTargets = await targetsFromCommandLine(
env,
build!,
<String>[],
defaultToAll: true,
enableRbe: false,
);
expect(selectedTargets, isNotNull);
expect(selectedTargets, isNotEmpty);
} finally {
testEnv.cleanup();
}
});
}

View File

@@ -0,0 +1,94 @@
// Copyright 2013 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:engine_tool/src/label.dart';
import 'package:litetest/litetest.dart';
void main() {
group('Label', () {
test('rejects relative paths', () {
expect(() => Label.parse('../foo/bar'), throwsFormatException);
expect(() => Label.parse('./foo/bar'), throwsFormatException);
expect(() => Label.parse('foo/bar'), throwsFormatException);
});
test('rejects starting with a number', () {
expect(() => Label.parse('//foo/1bar'), throwsFormatException);
expect(() => Label.parse('//foo/bar:1baz'), throwsFormatException);
});
test('rejects other invalid characters', () {
expect(() => Label.parse('//foo/bar!baz'), throwsFormatException);
expect(() => Label.parse('//foo/bar:baz!'), throwsFormatException);
});
test('rejects ending with a slash', () {
expect(() => Label.parse('//foo/bar/'), throwsFormatException);
expect(() => Label.parse('//foo/bar:baz/'), throwsFormatException);
});
test('rejects empty target name', () {
expect(() => Label.parse('//foo:'), throwsFormatException);
});
test('rejects empty package name', () {
expect(() => Label.parse(':bar'), throwsFormatException);
});
test('parses valid labels', () {
expect(Label.parse('//foo/bar'), Label('//foo/bar'));
});
test('parses valid labels with target', () {
expect(Label.parse('//foo/bar:baz'), Label('//foo/bar', 'baz'));
});
test('parses valid labels with underscores', () {
expect(Label.parse('//foo/bar_:_baz'), Label('//foo/bar_', '_baz'));
});
test('parses the GN format', () {
expect(Label.parseGn('//foo/bar'), Label('//foo/bar'));
expect(Label.parseGn('//foo/bar:baz'), Label('//foo/bar', 'baz'));
});
test('converts to string', () {
expect(Label('//foo/bar').toString(), '//foo/bar:bar');
expect(Label('//foo/bar', 'baz').toString(), '//foo/bar:baz');
});
test('converst to the ninja format', () {
expect(Label('//foo/bar').toNinjaLabel(), 'foo/bar:bar');
expect(Label('//foo/bar', 'baz').toNinjaLabel(), 'foo/bar:baz');
});
});
group('TargetPattern', () {
test('parses a valid label', () {
expect(TargetPattern.parse('//foo/bar'), TargetPattern('//foo/bar'));
expect(TargetPattern.parse('//foo/bar:baz'), TargetPattern('//foo/bar', 'baz'));
});
test('parses a wildcard package', () {
final TargetPattern result = TargetPattern.parse('//foo/...');
expect(result, TargetPattern('//foo/...'));
expect(result.target, isNull);
});
test('parses a wildcard target', () {
expect(TargetPattern.parse('//foo/bar:all'), TargetPattern('//foo/bar', 'all'));
});
test('converts to string', () {
expect(TargetPattern('//foo/bar').toString(), '//foo/bar:bar');
expect(TargetPattern('//foo/bar', 'baz').toString(), '//foo/bar:baz');
});
test('converts to the GN format', () {
expect(TargetPattern('//foo/bar/...').toGnPattern(), 'foo/bar/*');
expect(TargetPattern('//foo/bar', 'baz').toGnPattern(), 'foo/bar:baz');
expect(TargetPattern('//foo/bar', 'all').toGnPattern(), 'foo/bar:*');
});
});
}

View File

@@ -160,12 +160,30 @@ void main() {
'targets',
]);
expect(result, equals(0));
final List<String> expected = <String>[
'//flutter/display_list:display_list_unittests',
'//flutter/flow:flow_unittest',
'//flutter/fml:fml_arc_unittests',
];
final List<String> testLogs = stringsFromLogs(testEnvironment.testLogs);
for (final String testLog in testLogs) {
// Expect one of the expected targets to be in the output.
// Then remove it from the list of expected targets.
for (final String target in expected) {
if (testLog.contains(target)) {
expected.remove(target);
break;
}
}
}
expect(
testEnvironment.testLogs.length,
equals(4),
expected.isEmpty,
isTrue,
reason: 'All expected targets were found',
);
expect(testEnvironment.testLogs[1].message,
startsWith('//flutter/display_list:display_list_unittests'));
} finally {
testEnvironment.cleanup();
}

View File

@@ -39,16 +39,25 @@ void main() {
'win_test_config': winTestConfig,
};
final List<CannedProcess> cannedProcesses = <CannedProcess>[
CannedProcess((List<String> command) => command.contains('desc'),
stdout: fixtures.gnDescOutput()),
CannedProcess((List<String> command) => command.contains('outputs'),
stdout: 'display_list_unittests'),
];
test('test command executes test', () async {
final TestEnvironment testEnvironment = TestEnvironment.withTestEngine(
cannedProcesses: cannedProcesses,
// This test needs specific instrumentation. Ideally all tests should
// use per-test environments and not rely on global state, but that is a
// larger change (https://github.com/flutter/flutter/issues/148420).
cannedProcesses: <CannedProcess>[
CannedProcess(
(List<String> command) => command.contains('desc'),
stdout: '''
{
"//flutter/fml:display_list_unittests": {
"outputs": ["//out/host_debug/flutter/fml:display_list_unittests"],
"testonly": true,
"type": "executable"
}
}
''',
),
],
);
try {
final Environment env = testEnvironment.environment;
@@ -72,7 +81,28 @@ void main() {
test('test command skips non-testonly executables', () async {
final TestEnvironment testEnvironment = TestEnvironment.withTestEngine(
cannedProcesses: cannedProcesses,
// This test needs specific instrumentation. Ideally all tests should
// use per-test environments and not rely on global state, but that is a
// larger change (https://github.com/flutter/flutter/issues/148420).
cannedProcesses: <CannedProcess>[
CannedProcess(
(List<String> command) => command.contains('desc'),
stdout: '''
{
"//flutter/fml:display_list_unittests": {
"outputs": ["//out/host_debug/flutter/fml:display_list_unittests"],
"testonly": true,
"type": "executable"
},
"//third_party/protobuf:protoc": {
"outputs": ["//out/host_debug/third_party/protobuf:protoc"],
"testonly": false,
"type": "executable"
}
}
''',
),
],
);
try {
final Environment env = testEnvironment.environment;
@@ -82,10 +112,9 @@ void main() {
);
final int result = await runner.run(<String>[
'test',
'//third_party/protobuf:protoc',
'//...',
]);
expect(result, equals(1));
expect(testEnvironment.processHistory.length, lessThan(6));
expect(result, equals(0));
expect(testEnvironment.processHistory.where((ExecutedProcess process) {
return process.command[0].contains('protoc');
}), isEmpty);