diff --git a/engine/src/flutter/ci/analyze.sh b/engine/src/flutter/ci/analyze.sh index 6b57a819a0..ff2aeebafb 100755 --- a/engine/src/flutter/ci/analyze.sh +++ b/engine/src/flutter/ci/analyze.sh @@ -30,7 +30,16 @@ function follow_links() ( SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")") SRC_DIR="$(cd "$SCRIPT_DIR/../.."; pwd -P)" FLUTTER_DIR="$SRC_DIR/flutter" + +# This shell script takes one optional argument, the path to a dart-sdk/bin +# directory. If not specified, we default to the build output for +# host_debug_unopt. +if [[ $# -eq 0 ]] ; then DART_BIN="$SRC_DIR/out/host_debug_unopt/dart-sdk/bin" +else +DART_BIN="$1" +fi + DART="$DART_BIN/dart" if [[ ! -f "$DART" ]]; then diff --git a/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart b/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart index 2a1f3a6854..cf4bc92f83 100644 --- a/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart +++ b/engine/src/flutter/tools/engine_tool/lib/src/commands/command_runner.dart @@ -10,6 +10,7 @@ import 'build_command.dart'; import 'fetch_command.dart'; import 'flags.dart'; import 'format_command.dart'; +import 'lint_command.dart'; import 'query_command.dart'; import 'run_command.dart'; @@ -29,6 +30,7 @@ final class ToolCommandRunner extends CommandRunner { QueryCommand(environment: environment, configs: configs), BuildCommand(environment: environment, configs: configs), RunCommand(environment: environment, configs: configs), + LintCommand(environment: environment), ]; commands.forEach(addCommand); diff --git a/engine/src/flutter/tools/engine_tool/lib/src/commands/lint_command.dart b/engine/src/flutter/tools/engine_tool/lib/src/commands/lint_command.dart new file mode 100644 index 0000000000..6723790b9b --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/lib/src/commands/lint_command.dart @@ -0,0 +1,220 @@ +// 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:io' show Directory; +import 'dart:math'; + +import 'package:path/path.dart' as p; + +import '../dart_utils.dart'; +import '../environment.dart'; +import '../logger.dart'; +import '../proc_utils.dart'; +import '../worker_pool.dart'; +import 'command.dart'; +import 'flags.dart'; + +/// The different kind of linters we support. +enum Linter { + /// Dart linter + dart, + + /// Java linter + java, + + /// C/C++ linter + c, + + /// Python linter + python +} + +class _LinterDescription { + _LinterDescription(this.linter, this.cwd, this.command); + + final Linter linter; + final Directory cwd; + final List command; +} + +/// The root 'lint' command. +final class LintCommand extends CommandBase { + /// Constructs the 'lint' command. + LintCommand({ + required super.environment, + }) { + final String engineFlutterPath = environment.engine.flutterDir.path; + _linters[Linter.dart] = _LinterDescription( + Linter.dart, environment.engine.flutterDir, [ + p.join(engineFlutterPath, 'ci', 'analyze.sh'), + findDartBinDirectory(environment) + ]); + _linters[Linter.java] = + _LinterDescription(Linter.java, environment.engine.flutterDir, [ + findDartBinary(environment), + p.join(engineFlutterPath, 'tools', 'android_lint', 'bin', 'main.dart'), + ]); + _linters[Linter.c] = _LinterDescription( + Linter.c, + environment.engine.flutterDir, + [p.join(engineFlutterPath, 'ci', 'clang_tidy.sh')]); + _linters[Linter.python] = _LinterDescription( + Linter.python, + environment.engine.flutterDir, + [p.join(engineFlutterPath, 'ci', 'pylint.sh')]); + } + + final Map _linters = + {}; + + @override + String get name => 'lint'; + + @override + String get description => 'Lint the engine repository.'; + + @override + Future run() async { + // TODO(loic-sharma): Relax this restriction. + if (environment.platform.isWindows) { + environment.logger + .error('lint command is not supported on Windows (for now).'); + return 1; + } + final WorkerPool wp = + WorkerPool(environment, ProcessTaskProgressReporter(environment)); + + final Set tasks = {}; + for (final MapEntry entry in _linters.entries) { + tasks.add(ProcessTask( + entry.key.name, environment, entry.value.cwd, entry.value.command)); + } + final bool r = await wp.run(tasks); + + final bool verbose = globalResults![verboseFlag] as bool; + if (verbose) { + environment.logger.status('\nDumping failure logs\n'); + for (final ProcessTask pt in tasks) { + final ProcessArtifacts pa = pt.processArtifacts; + if (pa.exitCode == 0) { + continue; + } + environment.logger.status(pa.stdout); + environment.logger.status(pa.stderr); + } + } + return r ? 0 : 1; + } +} + +/// A WorkerPoolProgressReporter designed to work with ProcessTasks. +class ProcessTaskProgressReporter implements WorkerPoolProgressReporter { + /// Construct a new reporter. + ProcessTaskProgressReporter(this._environment); + + final Environment _environment; + Spinner? _spinner; + bool _finished = false; + int _longestName = 0; + + @override + void onRun(Set tasks) { + for (final WorkerTask task in tasks) { + _longestName = max(_longestName, task.name.length); + } + } + + @override + void onFinish() { + _finished = true; + _updateSpinner([]); + } + + List _makeProcessTaskList(WorkerPool pool) { + final List runningTasks = []; + for (final WorkerTask task in pool.running) { + if (task is! ProcessTask) { + continue; + } + runningTasks.add(task); + } + return runningTasks; + } + + @override + void onTaskStart(WorkerPool pool, WorkerTask task) { + final List running = _makeProcessTaskList(pool); + _updateSpinner(running); + } + + @override + void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]) { + final List running = _makeProcessTaskList(pool); + task as ProcessTask; + final ProcessArtifacts pa = task.processArtifacts; + final String dt = _formatDurationShort(task.runTime); + if (pa.exitCode != 0) { + final String paPath = task.processArtifactsPath; + _environment.logger.clearLine(); + _environment.logger.status( + 'FAIL: ${task.name.padLeft(_longestName)} after $dt [details in $paPath]'); + } else { + _environment.logger.clearLine(); + _environment.logger + .status('OKAY: ${task.name.padLeft(_longestName)} after $dt'); + } + _updateSpinner(running); + } + + void _updateSpinner(List tasks) { + if (_spinner != null) { + _spinner!.finish(); + _spinner = null; + } + if (_finished) { + return; + } + _environment.logger.clearLine(); + String runStatus = '['; + for (final ProcessTask pt in tasks) { + if (runStatus != '[') { + runStatus += ' '; + } + runStatus += pt.name; + } + if (tasks.isNotEmpty) { + runStatus += '...'; + } + runStatus += '] '; + _environment.logger.status('Linting $runStatus', newline: false); + _spinner = _environment.logger.startSpinner(); + } +} + +String _formatDurationShort(Duration dur) { + int micros = dur.inMicroseconds; + String r = ''; + if (micros >= Duration.microsecondsPerMinute) { + final int minutes = micros ~/ Duration.microsecondsPerMinute; + micros -= minutes * Duration.microsecondsPerMinute; + r += '${minutes}m'; + } + if (micros >= Duration.microsecondsPerSecond) { + final int seconds = micros ~/ Duration.microsecondsPerSecond; + micros -= seconds * Duration.microsecondsPerSecond; + if (r.isNotEmpty) { + r += '.'; + } + r += '${seconds}s'; + } + if (micros >= Duration.microsecondsPerMillisecond) { + final int millis = micros ~/ Duration.microsecondsPerMillisecond; + micros -= millis * Duration.microsecondsPerMillisecond; + if (r.isNotEmpty) { + r += '.'; + } + r += '${millis}ms'; + } + return r; +} diff --git a/engine/src/flutter/tools/engine_tool/lib/src/dart_utils.dart b/engine/src/flutter/tools/engine_tool/lib/src/dart_utils.dart new file mode 100644 index 0000000000..b75906bb16 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/lib/src/dart_utils.dart @@ -0,0 +1,56 @@ +// 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:ffi' as ffi show Abi; + +import 'package:path/path.dart' as p; +import 'environment.dart'; + +String _getAbiSubdirectory(ffi.Abi abi) { + switch (abi) { + case ffi.Abi.macosArm64: + return 'macos-arm64'; + case ffi.Abi.macosX64: + return 'macos-x64'; + case ffi.Abi.windowsArm64: + return 'windows-arm64'; + case ffi.Abi.windowsX64: + return 'windows-x64'; + case ffi.Abi.linuxArm: + return 'linux-arm'; + case ffi.Abi.linuxArm64: + return 'linux-arm64'; + case ffi.Abi.linuxIA32: + return 'linux-x86'; + case ffi.Abi.linuxX64: + return 'linux-x64'; + case ffi.Abi.androidArm: + case ffi.Abi.androidArm64: + case ffi.Abi.androidIA32: + case ffi.Abi.androidX64: + case ffi.Abi.androidRiscv64: + case ffi.Abi.fuchsiaArm64: + case ffi.Abi.fuchsiaX64: + case ffi.Abi.fuchsiaRiscv64: + case ffi.Abi.iosArm: + case ffi.Abi.iosArm64: + case ffi.Abi.iosX64: + case ffi.Abi.linuxRiscv32: + case ffi.Abi.linuxRiscv64: + case ffi.Abi.windowsIA32: + default: + throw UnsupportedError('Unsupported Abi $abi'); + } +} + +/// Returns a dart-sdk/bin directory path that is compatible with the host. +String findDartBinDirectory(Environment env) { + return p.join(env.engine.flutterDir.path, 'prebuilts', + _getAbiSubdirectory(env.abi), 'dart-sdk', 'bin'); +} + +/// Returns a dart-sdk/bin/dart file pthat that is executable on the host. +String findDartBinary(Environment env) { + return p.join(findDartBinDirectory(env), 'dart'); +} diff --git a/engine/src/flutter/tools/engine_tool/lib/src/proc_utils.dart b/engine/src/flutter/tools/engine_tool/lib/src/proc_utils.dart new file mode 100644 index 0000000000..e68cd3be49 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/lib/src/proc_utils.dart @@ -0,0 +1,118 @@ +// 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:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:process_runner/process_runner.dart'; + +import 'environment.dart'; +import 'json_utils.dart'; +import 'worker_pool.dart'; + +/// Artifacts from an exited sub-process. +final class ProcessArtifacts { + /// Constructs an instance of ProcessArtifacts from raw values. + ProcessArtifacts( + this.cwd, this.commandLine, this.exitCode, this.stdout, this.stderr, + {this.pid}); + + /// Constructs an instance of ProcessArtifacts from serialized JSON text. + factory ProcessArtifacts.fromJson(String serialized) { + final Map artifact = + jsonDecode(serialized) as Map; + final List errors = []; + final Directory cwd = Directory(stringOfJson(artifact, 'cwd', errors)!); + final List commandLine = + stringListOfJson(artifact, 'commandLine', errors)!; + final int exitCode = intOfJson(artifact, 'exitCode', errors)!; + final String stdout = stringOfJson(artifact, 'stdout', errors)!; + final String stderr = stringOfJson(artifact, 'stderr', errors)!; + return ProcessArtifacts(cwd, commandLine, exitCode, stdout, stderr); + } + + /// Constructs an instance of ProcessArtifacts from a file containing JSON. + factory ProcessArtifacts.fromFile(File file) { + return ProcessArtifacts.fromJson(file.readAsStringSync()); + } + + /// Saves ProcessArtifacts into file. + void save(File file) { + final Map data = {}; + if (pid != null) { + data['pid'] = pid!; + } + data['exitCode'] = exitCode; + data['stdout'] = stdout; + data['stderr'] = stderr; + data['cwd'] = cwd.absolute.path; + data['commandLine'] = commandLine; + file.writeAsStringSync(jsonEncode(data)); + } + + /// Creates a temporary file and saves the artifacts into it. + /// Returns the File. + File saveTemp() { + final Directory systemTemp = Directory.systemTemp; + final String prefix = pid != null ? 'et$pid' : 'et'; + final Directory artifacts = systemTemp.createTempSync(prefix); + final File resultFile = + File(p.join(artifacts.path, 'process_artifacts.json')); + save(resultFile); + return resultFile; + } + + /// Current working directory of process when it was spawned. + final Directory cwd; + + /// Full command line of process. + final List commandLine; + + /// Exit code. + final int exitCode; + + /// Stdout (may be empty). + final String stdout; + + /// Stdout (may be empty). + final String stderr; + + /// Pid (when available). + final int? pid; +} + +/// A WorkerTask that runs a process +class ProcessTask extends WorkerTask { + /// Construct a new process task with name, cwd, and command line. + ProcessTask(super.name, this._environment, this._cwd, this._commandLine); + + final Environment _environment; + final Directory _cwd; + final List _commandLine; + late ProcessArtifacts? _processArtifacts; + late String? _processArtifactsPath; + + @override + Future run() async { + final ProcessRunnerResult result = await _environment.processRunner + .runProcess(_commandLine, failOk: true, workingDirectory: _cwd); + _processArtifacts = ProcessArtifacts( + _cwd, _commandLine, result.exitCode, result.stdout, result.stderr, + pid: result.pid); + _processArtifactsPath = _processArtifacts!.saveTemp().path; + return result.exitCode == 0; + } + + /// Returns the ProcessArtifacts after run completes. + ProcessArtifacts get processArtifacts { + return _processArtifacts!; + } + + /// Returns the path that the process artifacts were saved in. + String get processArtifactsPath { + return _processArtifactsPath!; + } +} diff --git a/engine/src/flutter/tools/engine_tool/lib/src/worker_pool.dart b/engine/src/flutter/tools/engine_tool/lib/src/worker_pool.dart new file mode 100644 index 0000000000..c9ec02f4a1 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/lib/src/worker_pool.dart @@ -0,0 +1,148 @@ +// 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:async'; +import 'dart:collection'; + +import 'environment.dart'; + +/// A WorkerTask. +abstract class WorkerTask { + /// WorkerTask with a name. + WorkerTask(this.name); + + /// Name of worker task. + final String name; + + /// Run the task which is complete when the returned future completes. + /// Returns true if successful. + Future run(); + + /// Returns the run time of this task. + Duration get runTime { + if (_startTime == null || _finishTime == null) { + return Duration.zero; + } + return _finishTime!.difference(_startTime!); + } + + // When did this task start running? + DateTime? _startTime; + // When did this task finish running? + DateTime? _finishTime; +} + +/// A pool of worker tasks that will run numWorkers tasks at a time +/// until all of the tasks are finished. +class WorkerPool { + /// Construct a worker pool with a specific reporter and max concurrency + /// limit. + WorkerPool(this._environment, this._reporter, [this._maxConcurrency = 4]); + + final Environment _environment; + final WorkerPoolProgressReporter _reporter; + final int _maxConcurrency; + + late Completer _runCompleter; + bool _anyFailed = false; + final Set _running = {}; + final Set _pending = {}; + final Set _finished = {}; + + /// Run all tasks in the pool. Report progress via reporter. + /// Returns 0 on success and non-zero on failure. + Future run(Set tasks) async { + _environment.logger.info('Running ${tasks.length}'); + _runCompleter = Completer(); + _reporter.onRun(tasks); + _pending.addAll(tasks); + _runQueue(); + return _runCompleter.future; + } + + /// Returns the current set of pending tasks. + UnmodifiableSetView get pending { + return UnmodifiableSetView(_pending); + } + + /// Returns the current set of running tasks. + UnmodifiableSetView get running { + return UnmodifiableSetView(_running); + } + + /// Returns the current set of finished tasks. + UnmodifiableSetView get finished { + return UnmodifiableSetView(_finished); + } + + void _runQueue() { + if (_pending.isEmpty && _running.isEmpty) { + _reporter.onFinish(); + // Nothing left to do or running. + _runCompleter.complete(!_anyFailed); + return; + } + while (_running.length < _maxConcurrency && _pending.isNotEmpty) { + final WorkerTask task = _pending.elementAt(0); + _pending.remove(task); + _runTask(task); + } + } + + Future _runTask(WorkerTask task) async { + task._startTime = DateTime.now(); + final Future result = task.run(); + + _running.add(task); + _reporter.onTaskStart(this, task); + + Object? err; + late final bool r; + try { + r = await result; + } catch (e) { + err = e; + r = false; + } + _anyFailed = _anyFailed || !r; + task._finishTime = DateTime.now(); + + _running.remove(task); + _finished.add(task); + _reporter.onTaskDone(this, task, err); + + // Kick the queue again. + _runQueue(); + } +} + +/// WorkerPoolProgressReporter can be used to monitor worker pool progress. +abstract class WorkerPoolProgressReporter { + /// Invoked when [WorkerPool.run] is invoked. + void onRun(Set tasks); + + /// Invoked right before [WorkerPool.run] is returned from. + void onFinish(); + + /// Invoked right after a task has been started. + void onTaskStart(WorkerPool pool, WorkerTask task); + + /// Invoked right after a task has finished. + void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]); +} + +/// Useful for tests. +class NoopWorkerPoolProgressReporter implements WorkerPoolProgressReporter { + @override + void onRun(Set tasks) {} + + @override + void onFinish() {} + + @override + void onTaskStart(WorkerPool pool, WorkerTask task) {} + + @override + void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]) {} +} diff --git a/engine/src/flutter/tools/engine_tool/test/lint_command_test.dart b/engine/src/flutter/tools/engine_tool/test/lint_command_test.dart new file mode 100644 index 0000000000..11097ff28a --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/test/lint_command_test.dart @@ -0,0 +1,89 @@ +// 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:ffi' as ffi show Abi; +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/commands/command_runner.dart'; +import 'package:engine_tool/src/environment.dart'; +import 'package:engine_tool/src/logger.dart'; +import 'package:litetest/litetest.dart'; +import 'package:platform/platform.dart'; +import 'package:process_fakes/process_fakes.dart'; +import 'package:process_runner/process_runner.dart'; + +import 'fixtures.dart' as fixtures; + +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')) + as Map, + ); + + final BuilderConfig macTestConfig = BuilderConfig.fromJson( + path: 'ci/builders/mac_test_config.json', + map: convert.jsonDecode(fixtures.testConfig('Mac-12')) + as Map, + ); + + final BuilderConfig winTestConfig = BuilderConfig.fromJson( + path: 'ci/builders/win_test_config.json', + map: convert.jsonDecode(fixtures.testConfig('Windows-11')) + as Map, + ); + + final Map configs = { + 'linux_test_config': linuxTestConfig, + 'linux_test_config2': linuxTestConfig, + 'mac_test_config': macTestConfig, + 'win_test_config': winTestConfig, + }; + + (Environment, List>) macEnv(Logger logger) { + final List> runHistory = >[]; + return ( + Environment( + abi: ffi.Abi.macosArm64, + engine: engine, + platform: FakePlatform(operatingSystem: Platform.macOS), + processRunner: ProcessRunner( + processManager: FakeProcessManager(onStart: (List command) { + runHistory.add(command); + return FakeProcess(); + }, onRun: (List command) { + // Should not be executed. + assert(false); + return io.ProcessResult(81, 1, '', ''); + })), + logger: logger, + ), + runHistory + ); + } + + test('invoked linters', () async { + final Logger logger = Logger.test(); + final (Environment env, List> runHistory) = macEnv(logger); + final ToolCommandRunner runner = ToolCommandRunner( + environment: env, + configs: configs, + ); + final int result = await runner.run(['lint']); + expect(result, equals(0)); + expect(runHistory.length, greaterThanOrEqualTo(4)); + expect(runHistory[0].firstOrNull, contains('analyze.sh')); + }); +} diff --git a/engine/src/flutter/tools/engine_tool/test/proc_utils_test.dart b/engine/src/flutter/tools/engine_tool/test/proc_utils_test.dart new file mode 100644 index 0000000000..61cfe5a9d7 --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/test/proc_utils_test.dart @@ -0,0 +1,84 @@ +// 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:ffi' as ffi show Abi; +import 'dart:io' as io; + +import 'package:engine_repo_tools/engine_repo_tools.dart'; +import 'package:engine_tool/src/environment.dart'; +import 'package:engine_tool/src/logger.dart'; +import 'package:engine_tool/src/proc_utils.dart'; +import 'package:engine_tool/src/worker_pool.dart'; +import 'package:litetest/litetest.dart'; +import 'package:platform/platform.dart'; +import 'package:process_fakes/process_fakes.dart'; +import 'package:process_runner/process_runner.dart'; + +void main() { + final Engine engine; + try { + engine = Engine.findWithin(); + } catch (e) { + io.stderr.writeln(e); + io.exitCode = 1; + return; + } + + (Environment, List>) macEnv(Logger logger) { + final List> runHistory = >[]; + return ( + Environment( + abi: ffi.Abi.macosArm64, + engine: engine, + platform: FakePlatform(operatingSystem: Platform.macOS), + processRunner: ProcessRunner( + processManager: FakeProcessManager(onStart: (List command) { + runHistory.add(command); + switch (command) { + case ['success']: + return FakeProcess(stdout: 'stdout success'); + case ['failure']: + return FakeProcess(exitCode: 1, stdout: 'stdout failure'); + default: + return FakeProcess(); + } + }, onRun: (List command) { + // Should not be executed. + assert(false); + return io.ProcessResult(81, 1, '', ''); + })), + logger: logger, + ), + runHistory + ); + } + + test('process queue success', () async { + final Logger logger = Logger.test(); + final (Environment env, _) = macEnv(logger); + final WorkerPool wp = WorkerPool(env, NoopWorkerPoolProgressReporter()); + final ProcessTask task = + ProcessTask('S', env, io.Directory.current, ['success']); + final bool r = await wp.run({task}); + expect(r, equals(true)); + expect(task.processArtifacts.exitCode, equals(0)); + final ProcessArtifacts loaded = + ProcessArtifacts.fromFile(io.File(task.processArtifactsPath)); + expect(loaded.stdout, equals('stdout success')); + }); + + test('process queue failure', () async { + final Logger logger = Logger.test(); + final (Environment env, _) = macEnv(logger); + final WorkerPool wp = WorkerPool(env, NoopWorkerPoolProgressReporter()); + final ProcessTask task = + ProcessTask('F', env, io.Directory.current, ['failure']); + final bool r = await wp.run({task}); + expect(r, equals(false)); + expect(task.processArtifacts.exitCode, notEquals(0)); + final ProcessArtifacts loaded = + ProcessArtifacts.fromFile(io.File(task.processArtifactsPath)); + expect(loaded.stdout, equals('stdout failure')); + }); +} diff --git a/engine/src/flutter/tools/engine_tool/test/worker_pool_test.dart b/engine/src/flutter/tools/engine_tool/test/worker_pool_test.dart new file mode 100644 index 0000000000..ad99d3700c --- /dev/null +++ b/engine/src/flutter/tools/engine_tool/test/worker_pool_test.dart @@ -0,0 +1,126 @@ +// 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:ffi' as ffi show Abi; +import 'dart:io' as io; + +import 'package:engine_repo_tools/engine_repo_tools.dart'; +import 'package:engine_tool/src/environment.dart'; +import 'package:engine_tool/src/logger.dart'; +import 'package:engine_tool/src/worker_pool.dart'; +import 'package:litetest/litetest.dart'; +import 'package:platform/platform.dart'; +import 'package:process_fakes/process_fakes.dart'; +import 'package:process_runner/process_runner.dart'; + +class TestWorkerPoolProgressReporter implements WorkerPoolProgressReporter { + int _successCount = 0; + int _errorCount = 0; + final List _errors = []; + + @override + void onRun(Set tasks) {} + + @override + void onFinish() {} + + @override + void onTaskStart(WorkerPool pool, WorkerTask task) {} + + @override + void onTaskDone(WorkerPool pool, WorkerTask task, [Object? err]) { + if (err == null) { + _successCount++; + return; + } + _errorCount++; + _errors.add(err); + } +} + +class SuccessfulTask extends WorkerTask { + SuccessfulTask() : super('s'); + + @override + Future run() async { + return true; + } +} + +class FailureTask extends WorkerTask { + FailureTask() : super('f'); + + @override + Future run() async { + throw ArgumentError('test'); + } +} + +void main() { + final Engine engine; + try { + engine = Engine.findWithin(); + } catch (e) { + io.stderr.writeln(e); + io.exitCode = 1; + return; + } + + (Environment, List>) macEnv(Logger logger) { + final List> runHistory = >[]; + return ( + Environment( + abi: ffi.Abi.macosArm64, + engine: engine, + platform: FakePlatform(operatingSystem: Platform.macOS), + processRunner: ProcessRunner( + processManager: FakeProcessManager(onStart: (List command) { + runHistory.add(command); + switch (command) { + case ['success']: + return FakeProcess(stdout: 'stdout success'); + case ['failure']: + return FakeProcess(exitCode: 1, stdout: 'stdout failure'); + default: + return FakeProcess(); + } + }, onRun: (List command) { + // Should not be executed. + assert(false); + return io.ProcessResult(81, 1, '', ''); + })), + logger: logger, + ), + runHistory + ); + } + + test('worker pool success', () async { + final Logger logger = Logger.test(); + final (Environment env, _) = macEnv(logger); + final TestWorkerPoolProgressReporter reporter = + TestWorkerPoolProgressReporter(); + final WorkerPool wp = WorkerPool(env, reporter); + final WorkerTask task = SuccessfulTask(); + final bool r = await wp.run({task}); + expect(r, equals(true)); + expect(reporter._successCount, equals(1)); + expect(reporter._errorCount, equals(0)); + expect(reporter._errors.length, equals(0)); + }); + + test('worker pool failure', () async { + final Logger logger = Logger.test(); + final (Environment env, _) = macEnv(logger); + final TestWorkerPoolProgressReporter reporter = + TestWorkerPoolProgressReporter(); + final WorkerPool wp = WorkerPool(env, reporter); + final WorkerTask task = FailureTask(); + final bool r = await wp.run({task}); + expect(r, equals(false)); + expect(reporter._successCount, equals(0)); + expect(reporter._errorCount, equals(1)); + expect(reporter._errors.length, equals(1)); + }); +}